If you're as excited about React's new features as I am, you've probably been keeping an eye on the experimental builds. In this post, we're going ...
For further actions, you may consider blocking this person and/or reporting abuse
Wow. Thanks for sharing!
Iām glad you found this interesting! Hopefully this prepares you for when it is properly ready! š„³
Yesss. Thank you.
Looks awesome, thanks for the clear and consise explanation š
It's such a pleasure and thank you for the encouraging feedback!
Thank you @barrymichaeldoyle for this great explanation.
How do we handle errors? What to do when network request fails? Is there any mechanism to undo the optimistic update?
Sorry I've taken so long to get back to you.
The way the useOptimistic hook works is that the optimistic update resets when the the asynchronous form action is completed and the actual rendered value gets replaced by the new todos. It's not really shown in my example code in this post.
So in the case of an error - which will be handled in
createTodo
- the optimistic value will be cleared when the promise rejects because todos doesn't change. The way you decide to handle an error specifically is up to you e.g. you could render a toast, or show an error message under the todos list, up to you.Why useOptimistic is undefined in my app after I installed like so
npm install react@experimental react-dom@experimental
I tried import { useOptimistic } from 'react' as well but does not work.
It keeps erroring out saying
0__.useOptimistic) is not a function or its return value is not iterable
What if you mutate your data somewhere else? How would you use useOptimistic hook then? Perhaps, with state management libraries such as zustand?
You can wrap your action into a transition
`const [isPending, startTransition] = useTransition();
const onUpdate = () => {
startTransition(()=> {
optimisticUpdate();
})
}
`
In that scenario I'd recommend going with something like zustand yes.