Complete the code to update the UI immediately after a user action.
const [items, setItems] = useState([]);
function addItem(newItem) {
setItems([1]);
// send update to server
}We use [...items, newItem] to create a new array including the new item, updating state immediately.
Complete the code to rollback the UI update if the server request fails.
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]);
}
}If the server request fails, we restore the previous state saved in previousItems.
Fix the error in the optimistic update pattern by completing the missing part.
function handleDelete(id) {
const previousItems = items;
setItems(items.filter(item => item.id !== [1]));
// send delete request
}We compare each item's id to the given id to filter out the deleted item.
Fill both blanks to optimistically update and rollback a list after editing an item.
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);
}
}We check if item.id matches updatedItem.id and replace it with updatedItem for optimistic update.
Fill all three blanks to implement optimistic update with React Query's mutation.
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]);
}
});We add newItem optimistically, rollback to context.previousItems on error, and invalidate the 'items' query after mutation settles.