useSWRMutation: optimistic updates for multiple keys + extracting custom hook #4182
Unanswered
gweiermann
asked this question in
Q&A
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Hey, I’d love some feedback on how to handle optimistic updates with useSWRMutation when multiple cache keys are involved, and how to structure this cleanly in a reusable hook.
Setup
With my current API design I have several routes where the data overlaps, e.g.:
/api/all-users/api/all-users-with-joined-dataI want to use a mutation to add a new user. A simplified version looks like this:
Here, one key is passed directly to
useSWRMutationand another is handled inonSuccess. To make it more consistent, I can introduce a dummy key:So far, so good.
Problem 1: Optimistic updates for multiple keys
This becomes awkward once I want optimistic updates.
Using
optimisticDatawithtrigger(...), I can optimistically update the first key, but not the second. For the second key I’d have to manually update it later (e.g. inonSuccess), which means the second optimistic update is delayed until after the mutation finishes:Question 1:
Is there a way to:
optimisticDatato multiple keys immediately (before the network request resolves),useSWRMutationprovides?Or is manually calling
mutatewithoptimisticDataon each key the intended approach here?Problem 2: Extracting into a reusable hook while using optimisticData
I’d like to move the
useSWRMutationcall into a separate hook:The problem: inside the hook I’ve lost access to the
newUservalue that was passed totrigger. I could try to wrap/monkey-patchtriggerto capture the argument and store it in some state, but that feels like an implementation detail I shouldn’t rely on.Question 2:
Is there a recommended pattern for:
useAddUserhook,triggerarguments just to reuse them inonSuccess/mutatecalls?Or is this whole approach (multiple overlapping keys + shared optimistic updates) considered a code smell, and I should rather rethink my API/cache design?
I’m very interested in your opinions and patterns you use in similar situations!
Beta Was this translation helpful? Give feedback.
All reactions