T
TanStack3y ago
sensitive-blue

Optimistic updates with sorted lists

For a list of todos sorted by due date, what is the best way to handle optimistic updates for a new to do? https://tkdodo.eu/blog/mastering-mutations-in-react-query mentions it as one of those cases where things can get complex fairly quickly but it is a required feature for what I'm building.. My guess is that you add it to the cache and run a local sort. This seems fine....? Am I missing something. Also, one other question - for optimistic updates, I am setting the temporary id as Math.random(). This required me to change the type of ToDoData from {id: string} to {id?: string} so that I know when the id is undefined and I can prevent actions like clicking the to do to see a detailed view. Is this the best practice? Kinda sucks that my type has id as optional just to accomodate optimistic updates.
6 Replies
like-gold
like-gold3y ago
When I’ve done stuff like this in the past I’ve used a UUID as a temporary ID, no need for the id to be optional on your type then. But on top of that, added a flag of isOptimistic: true to show some loading and/or prevent navigation to a detail view before it’s been confirmed by the server.
sensitive-blue
sensitive-blueOP3y ago
Got it. Curious if that is best practice. Any resources around this that you based your decision off of? Just don't want to keep refactoring
like-gold
like-gold3y ago
Hmm... no I can’t remember any particular reference for that "pattern". I would note that this approach is relatively dumb in that I’d expect to invalidate the query (while keeping the current data) to get the actual state from the server (and thus remove the isOptimistic key).
flat-fuchsia
flat-fuchsia3y ago
have you seen the new way to do optimistic updates in v5? should simplify cases like this a bit
flat-fuchsia
flat-fuchsia3y ago
Optimistic Updates | TanStack Query Docs
React Query provides two ways to optimistically update your UI before a mutation has completed. You can either use the onMutate option to update your cache directly, or leverage the returned variables to update your UI from the useMutation result. Via the UI
like-gold
like-gold3y ago
The example with the mutation is key is really nice. Great API as always @TkDodo 🔮 🙏🏻

Did you find this page helpful?