0
0
NextJSframework~10 mins

Optimistic state updates in NextJS - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a state variable for the count using React's useState.

NextJS
const [count, [1]] = useState(0);
Drag options to blanks, or click blank then click option'
AupdateCount
BcountSet
CsetCount
DchangeCount
Attempts:
3 left
💡 Hint
Common Mistakes
Using a setter name that doesn't start with 'set'.
Mixing the order of the array destructuring.
2fill in blank
medium

Complete the code to optimistically update the count state before the server confirms.

NextJS
function increment() {
  setCount(count [1] 1);
  // call server update here
}
Drag options to blanks, or click blank then click option'
A*
B+
C-
D/
Attempts:
3 left
💡 Hint
Common Mistakes
Using subtraction instead of addition.
Using multiplication or division which changes the value incorrectly.
3fill in blank
hard

Fix the error in the async function to update the count optimistically and revert if the server fails.

NextJS
async function updateCount() {
  const oldCount = count;
  setCount(count + 1);
  try {
    await fetch('/api/update', { method: 'POST' });
  } catch (error) {
    setCount([1]);
  }
}
Drag options to blanks, or click blank then click option'
AoldCount
Bcount
C0
Dcount + 1
Attempts:
3 left
💡 Hint
Common Mistakes
Reverting to the current count which is already incremented.
Setting count to zero which resets incorrectly.
4fill in blank
hard

Fill both blanks to create an optimistic update with a rollback on failure.

NextJS
async function toggle() {
  const previous = [1];
  setCount(count [2] 1);
  try {
    await fetch('/api/toggle', { method: 'POST' });
  } catch {
    setCount(previous);
  }
}
Drag options to blanks, or click blank then click option'
Acount
BsetCount
C+
D-
Attempts:
3 left
💡 Hint
Common Mistakes
Saving the setter function instead of the count value.
Using subtraction instead of addition for increment.
5fill in blank
hard

Fill all three blanks to implement an optimistic update with rollback and server confirmation.

NextJS
async function addItem(item) {
  const previousItems = [1];
  setItems([...items, [2]]);
  try {
    await fetch('/api/add', {
      method: 'POST',
      body: JSON.stringify({ item: [3] })
    });
  } catch {
    setItems(previousItems);
  }
}
Drag options to blanks, or click blank then click option'
Aitems
Bitem
DsetItems
Attempts:
3 left
💡 Hint
Common Mistakes
Saving the setter function instead of the items list.
Using wrong variable names for the new item.
Not sending the item in the request body.