Complete the code to create a state variable for the count using React's useState.
const [count, [1]] = useState(0);
The setter function for a state variable named count is conventionally named setCount.
Complete the code to optimistically update the count state before the server confirms.
function increment() {
setCount(count [1] 1);
// call server update here
}To increase the count by one, use the plus operator +.
Fix the error in the async function to update the count optimistically and revert if the server fails.
async function updateCount() {
const oldCount = count;
setCount(count + 1);
try {
await fetch('/api/update', { method: 'POST' });
} catch (error) {
setCount([1]);
}
}If the server update fails, revert the count to the old value stored in oldCount.
Fill both blanks to create an optimistic update with a rollback on failure.
async function toggle() {
const previous = [1];
setCount(count [2] 1);
try {
await fetch('/api/toggle', { method: 'POST' });
} catch {
setCount(previous);
}
}Save the current count in previous before updating. Then add 1 to count for optimistic update.
Fill all three blanks to implement an optimistic update with rollback and server confirmation.
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);
}
}Save the current items list in previousItems. Add the new item optimistically to the list. Send the item in the server request body.