T
TanStack2y ago
adverse-sapphire

Exposing mutation state through zustand

We have a complex scenario where a mutation is triggered from one part of the application, but its loading state is displayed in a different part. I'm not familiar with a mechanism that allows sharing the inner state of a useMutation call (isLoading, isSuccess etc) like we can with useQuery, so I want to sync it to a zustand store:
const useStore = create(set => ({
state: 'inactive',
setState(state) {
set(() => ({ state }));
}
}));

function Component() {
const setState = useStore(store => store.setState)
mutation = useMutation({
mutationFn() {
setState('loading');
...
},
onSuccess() {
setState('active');
...
}
})
}
const useStore = create(set => ({
state: 'inactive',
setState(state) {
set(() => ({ state }));
}
}));

function Component() {
const setState = useStore(store => store.setState)
mutation = useMutation({
mutationFn() {
setState('loading');
...
},
onSuccess() {
setState('active');
...
}
})
}
I was wondering if there is a better way to achieve this? I also considered using useEffect but the direct approach I showed in the snippet seemed better in my eyes.
4 Replies
conscious-sapphire
conscious-sapphire2y ago
useMutationState is your friend
adverse-sapphire
adverse-sapphireOP2y ago
Thanks! Can I reset a mutation from useMutationState? The object I get does not seem to have all the options as the useMutation return value
conscious-sapphire
conscious-sapphire2y ago
You can only reset a mutation if you have access to the useMutation
adverse-sapphire
adverse-sapphireOP2y ago
So IIUC my options are either to lift the useMutation call all the way up and expose the mutation via context, or sync it via useEffect to a zustand store?

Did you find this page helpful?