|
3 | 3 | Start with a basic form submission that asynchronously updates likes:
|
4 | 4 |
|
5 | 5 | 1. Add our own implementation of `optimisticLikes` with `useState`. Notice how
|
6 |
| - `likes` becomes useless / unused. We set it but nothing uses it. |
| 6 | + `likes` becomes useless / unused. We set it but nothing uses it. We can also see |
| 7 | + it becomes difficult to reconcile our optimistic likes and the real likes when |
| 8 | + there's an error. |
7 | 9 |
|
8 |
| -2. Refactor `onSubmit={submit}` to `action={action}` and now the homegrown optimistic likes |
9 |
| - don't work. |
| 10 | +2. Refactor `onSubmit={submit}` to `action={action}` and now the homegrown optimistic |
| 11 | + likes don't work. Switching to `useOptimistic` will work though since it's made to |
| 12 | + work with form actions. |
10 | 13 |
|
11 |
| -3. Refactor to useOptimistic, a hook that appears to be designed for form actions: |
| 14 | +3. With useOptimistic, go back to `onSubmit={submit}` and it wont work. It's nice to show |
| 15 | + the console because it will say we can't do `useOptimistic` without a transition (which |
| 16 | + is what actions were giving us). We can add `startTransition` though if we want it to |
| 17 | + work with `onSubmit` |
12 | 18 |
|
13 |
| -```ts |
14 |
| -const [error, setError] = useState('') |
15 |
| -const [likes, setLikes] = useState(0) |
16 |
| - |
17 |
| -const [optimisticLikes, setOptimisticLikes] = useOptimistic( |
18 |
| - likes, |
19 |
| - (currentLikes, newOptimisticLikes: number) => { |
20 |
| - return newOptimisticLikes |
21 |
| - } |
22 |
| -) |
23 |
| - |
24 |
| -async function action() { |
25 |
| - setOptimisticLikes(optimisticLikes + 1) |
26 |
| - const data = (await updateDatabase(optimisticLikes + 1).then((r) => r.json())) as ResponseData |
27 |
| - |
28 |
| - if (!data.error) { |
29 |
| - console.log(data.likes) |
30 |
| - setLikes(data.likes) |
31 |
| - } else { |
32 |
| - setLikes(data.likes) |
33 |
| - setError(data.error) |
34 |
| - } |
35 |
| -} |
36 |
| -``` |
37 |
| - |
38 |
| -4. Now with useOptimistic, if we go back and re-factor to `onSubmit={submit}`, we can see a warning: |
39 |
| - |
40 |
| -Warning: An optimistic state update occurred outside a transition or action. To fix, move the update to an action, or wrap with startTransition. |
| 19 | +"Warning: An optimistic state update occurred outside a transition or action. To fix, move the update to an action, or wrap with startTransition." |
0 commit comments