Complete the code to update the UI immediately when a user clicks the button.
function handleClick() {
setState({ loading: true });
updateUI({ optimistic: [1] });
sendRequest();
}Setting optimistic to true updates the UI immediately, showing the user the expected result before the server responds.
Complete the code to rollback UI changes if the server request fails.
async function saveData() {
try {
await sendRequest();
} catch (error) {
setState({ data: [1] });
}
}If the request fails, we restore the UI to previousData to undo the optimistic update.
Fix the error in the optimistic update function by completing the missing part.
function optimisticUpdate(state, action) {
return {
...state,
items: state.items.[1](action.item),
};
}Using concat adds the new item to the list without mutating the original array, which is important for state updates.
Fill both blanks to create an optimistic UI update that shows loading and adds the new item.
function updateState(state, action) {
return {
...state,
loading: [1],
items: state.items.[2](action.item),
};
}Setting loading to true shows the UI is waiting, and using concat adds the new item optimistically.
Fill all three blanks to implement optimistic UI with rollback on failure.
async function saveItem(state, action) {
const previousItems = state.items;
setState({
items: state.items.[1](action.item),
loading: [2],
});
try {
await sendRequest(action.item);
setState({ loading: [3] });
} catch {
setState({ items: previousItems, loading: false });
}
}We optimistically add the item with concat, set loading to true while waiting, and set loading to false after success.
