0
0
NextJSframework~10 mins

Optimistic updates pattern 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 update the UI immediately after a user action.

NextJS
const [items, setItems] = useState([]);

function addItem(newItem) {
  setItems([1]);
  // send update to server
}
Drag options to blanks, or click blank then click option'
A[...items, newItem]
Bitems.push(newItem)
Citems.concat()
Ditems.pop()
Attempts:
3 left
💡 Hint
Common Mistakes
Using push() which mutates the array and does not update state correctly.
Using pop() which removes items instead of adding.
2fill in blank
medium

Complete the code to rollback the UI update if the server request fails.

NextJS
async function addItem(newItem) {
  const previousItems = items;
  setItems([...items, newItem]);
  try {
    await fetch('/api/add', { method: 'POST', body: JSON.stringify(newItem) });
  } catch (error) {
    setItems([1]);
  }
}
Drag options to blanks, or click blank then click option'
A[newItem]
Bitems
C[]
DpreviousItems
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to reset to an empty array instead of previous state.
Using current items which already include the new item.
3fill in blank
hard

Fix the error in the optimistic update pattern by completing the missing part.

NextJS
function handleDelete(id) {
  const previousItems = items;
  setItems(items.filter(item => item.id !== [1]));
  // send delete request
}
Drag options to blanks, or click blank then click option'
Aid
Bitem
Citems
Dindex
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'item' which is the whole object, not the id.
Using 'items' which is the array, not a single id.
4fill in blank
hard

Fill both blanks to optimistically update and rollback a list after editing an item.

NextJS
async function editItem(updatedItem) {
  const previousItems = items;
  setItems(items.map(item => item.id === [1] ? [2] : item));
  try {
    await fetch('/api/edit', { method: 'POST', body: JSON.stringify(updatedItem) });
  } catch {
    setItems(previousItems);
  }
}
Drag options to blanks, or click blank then click option'
AupdatedItem.id
BupdatedItem
Citem.id
Ditem
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong variables for comparison or replacement.
Not replacing the item correctly in the map.
5fill in blank
hard

Fill all three blanks to implement optimistic update with React Query's mutation.

NextJS
const mutation = useMutation({
  mutationFn: newItem => fetch('/api/add', { method: 'POST', body: JSON.stringify(newItem) }),
  onMutate: async newItem => {
    await queryClient.cancelQueries('items');
    const previousItems = queryClient.getQueryData('items');
    queryClient.setQueryData('items', old => [...old, [1]]);
    return { previousItems };
  },
  onError: (err, newItem, context) => {
    queryClient.setQueryData('items', [2]);
  },
  onSettled: () => {
    queryClient.invalidateQueries([3]);
  }
});
Drag options to blanks, or click blank then click option'
AnewItem
Bcontext.previousItems
C'items'
D'newItem'
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong keys or variables in queryClient methods.
Not returning previous state for rollback.