Write data and handle failure
Chapter 4 of 6
Replace the tracker’s click handler with a form action. useActionState exposes the pending state and the latest result. Keep the count in Fate so both panels continue to read the same record.
import { useActionState } from 'react';
import { useFateClient } from 'react-fate';
export function AdvanceProgress() {
const fate = useFateClient();
const [result, advance, pending] = useActionState(
fate.actions.progress.advance,
null,
);
return (
<form action={() => advance({})}>
<button disabled={pending} type="submit">
{pending ? 'Saving…' : 'Read one page'}
</button>
{result?.error && <p role="alert">Could not save progress. Try again.</p>}
</form>
);
}
Use fate.actions for a React action or form. Use fate.mutations when you want to await a write directly, such as in an event handler. Handle the returned error and catch thrown failures when calling the imperative API.
Add optimism when the server is slow
For a future server mutation, imagine a reader selects “Read one page” while connected to a slow network. An optimistic function can show the increment immediately while the server write is pending. Use the current cached value and return undefined if that field is missing. Fate can replay pending functions after other writes, so keep the function pure. When the mutation fails, Fate rolls back the optimistic patch.
Treat validation errors as feedback near the form. Let thrown errors from a React Action reach an error boundary. If the user retries after an ambiguous network failure, a server-backed increment may need an idempotency key so the same click only counts once.
Try it
Mount the form next to ProgressSummary from chapter 2. Submit twice and follow the data flow from the action to the mutation, store, view, and label. If you wire a backend, repeat with network throttling and a deliberately rejected write. Check the pending label, error message, and restored count.