Sub topic 9
Handling failures and showing the rollback
This chapter assumes you know useState, props, async/await, and how a form action calls a server function. It also assumes you have read the earlier chapters on useOptimistic and on how the optimistic value is replaced by real state.
What happens when a request fails
An optimistic update is a guess that the server will accept the change. Sometimes the guess is wrong. The network drops, the server rejects the input, or the user's session has expired.
You do not write rollback code for this case. The optimistic value only lives while the Action runs. When the Action finishes, React renders again with the real state passed to useOptimistic. If the request failed, the parent never added the message to messages. The optimistic message therefore disappears.
The rollback works, but it is silent. The user sees a message appear and then vanish, with no explanation. Your job is to explain what happened.
Catching the error inside the Action
Wrap the server call in try/catch and store a message in ordinary state. This example is the message thread from the earlier chapters, with error handling added.
import { useOptimistic, useState } from "react";
function Thread({ messages, sendMessage }) {
const [error, setError] = useState(null);
const [optimisticMessages, addOptimisticMessage] = useOptimistic(
messages,
(currentMessages, text) => [
...currentMessages,
{ id: crypto.randomUUID(), text, sending: true },
]
);
async function formAction(formData) {
const text = formData.get("message");
setError(null);
addOptimisticMessage(text);
try {
await sendMessage(text);
} catch {
setError("Could not send your message. Please try again.");
}
}
return (
<>
<ul>
{optimisticMessages.map((m) => (
<li key={m.id}>{m.text}</li>
))}
</ul>
{error && <p role="alert">{error}</p>}
<form action={formAction}>
<input type="text" name="message" />
<button type="submit">Send</button>
</form>
</>
);
}Follow the order of events in formAction:
setError(null)clears any error from an earlier attempt, so a stale error does not stay on screen during a retry.addOptimisticMessage(text)shows the message immediately.await sendMessage(text)waits for the server.- If the call throws,
catchstores the error text. - The Action ends. React drops the optimistic message, because
messagesnever changed, and shows the error.
The role="alert" attribute makes screen readers announce the error when it appears. Without it, a user who cannot see the screen would not learn that the message was lost.
Why the catch block matters
If you leave out try/catch, a failed sendMessage throws out of the Action. The optimistic message still reverts, but the error goes to the nearest error boundary or surfaces as an unhandled rejection, depending on how the Action was started. For a routine failure such as a lost connection, you usually want a small inline message, not a full error screen. Catching the error yourself keeps the failure local.
Keeping the user's text
The version above has one usability problem. A form action resets uncontrolled fields after it runs, so the user's text is gone after a failure. They must retype it.
A simple fix is to put the failed text in state and use it as the input's defaultValue.
import { useOptimistic, useState } from "react";
function Thread({ messages, sendMessage }) {
const [failedText, setFailedText] = useState("");
const [error, setError] = useState(null);
const [optimisticMessages, addOptimisticMessage] = useOptimistic(
messages,
(currentMessages, text) => [
...currentMessages,
{ id: crypto.randomUUID(), text, sending: true },
]
);
async function formAction(formData) {
const text = formData.get("message");
setError(null);
setFailedText("");
addOptimisticMessage(text);
try {
await sendMessage(text);
} catch {
setFailedText(text);
setError("Could not send your message. Please try again.");
}
}
return (
<>
<ul>
{optimisticMessages.map((m) => (
<li key={m.id}>{m.text}</li>
))}
</ul>
{error && <p role="alert">{error}</p>}
<form action={formAction}>
<input
type="text"
name="message"
key={failedText}
defaultValue={failedText}
/>
<button type="submit">Send</button>
</form>
</>
);
}Changing the key makes React create a fresh input, so the new defaultValue takes effect.
Common mistakes
| Mistake | Result | Fix |
|---|---|---|
| Showing no error | The message vanishes with no explanation | Store an error in state and render it |
| Never clearing the old error | A stale error stays visible during a retry | Call `setError(null)` at the start of the Action |
| Calling the optimistic setter outside an Action | React warns, and the update may not revert as expected | Call it inside a form action or `startTransition` |
| Swallowing the error with an empty `catch` | The user is not told the request failed | Set an error message in `catch` |
Exercise
In the failing thread example, the server rejects a message. Which part of the code removes the optimistic message from the list, and what does your catch block need to do?
Show answer
React removes it. When the Action ends, useOptimistic returns the real messages prop, which does not include the failed message. The catch block does not touch the list. It only stores an error message in state so the user knows why the message disappeared.
Exercise
A user submits a message while offline. After the failure, the input is empty and no text is shown anywhere. Name two changes that would improve this.
Show answer
Render an error message, for example in a paragraph with role="alert", and keep the failed text by storing it in state and using it as the input's defaultValue (with a changing key so the input remounts).