TanStackT
TanStack5mo ago
3 replies
ill-bronze

"Nesting" mutations?

I've got a core useUpdate which does a mutation and invalidates some queries in the
onSuccess
.

I've got another useArchive which is really just an update, and should do the same invalidations as useUpdate, but then also a few more things (like some other invalidations) in its own
onSuccess
.

But then I've got a third Sidebar component, which uses useArchive in an event handler, and then has its own
onSuccess
logic (e.g., close the sidebar).

Is there anything particularly wrong with defining a "nested" mutation? Something like:

function useUpdate() {
  return useMutation({
    mutationFn: (foo) => { /* update mutation */ },
    onSuccess() { /* post-update stuff */ }
  });
}

function useArchive() {
  const {mutateAsync: update} = useUpdate();
  return useMutation({
    mutationFn: (foo) => update(foo),
    onSuccess() { /* post-archive stuff */ }
  });
}

function Sidebar() {
    const {mutate: archive} = useArchive();
    const foo = {foo: 'bar'};

    const onArchive = () => archive(foo, {
      onSuccess() { /* post-event stuff */ }
    });

    // ...
}
Was this page helpful?