Complete the code to trigger an optimistic update by immediately updating the UI state.
function handleClick() {
setData([1]);
fetch('/api/update', { method: 'POST' });
}We use setData(newData) to immediately update the UI before the server responds.
Complete the code to rollback the optimistic update if the server request fails.
async function handleSubmit() {
const previous = data;
setData(newData);
try {
await fetch('/api/save', { method: 'POST' });
} catch (error) {
setData([1]);
}
}If the server request fails, we restore the previous data to rollback the optimistic update.
Fix the error in the code to correctly update the UI optimistically and handle server response.
function updateItem(item) {
setItems(items.map(i => i.id === item.id ? [1] : i));
fetch('/api/items/' + item.id, {
method: 'PUT',
body: JSON.stringify(item)
});
}i which does not update.We replace the matching item with the updated item to reflect the optimistic update.
Fill both blanks to create an optimistic update with rollback on failure.
async function saveUser(newUser) {
const oldUser = [1];
setUser(newUser);
try {
await fetch('/api/user', { method: 'POST', body: JSON.stringify(newUser) });
} catch {
setUser([2]);
}
}We save the old user state before updating, then restore it if the server call fails.
Fill all three blanks to implement optimistic update with proper state and error handling.
function useOptimisticUpdate() {
const [data, setData] = useState(null);
async function update(newData) {
const previous = [1];
setData([2]);
try {
await fetch('/api/data', { method: 'PUT', body: JSON.stringify(newData) });
} catch {
setData([3]);
}
}
return [data, update];
}We save the current data as previous, update to newData optimistically, and revert to previous on error.
