TanStackT
TanStack3y ago
4 replies
uncertain-scarlet

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');
      ...
    }
  })
}


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.
Was this page helpful?