Skip to content

Sequential mutatoins with data issue #147

@mrodyhin

Description

@mrodyhin

Hi. I found an issue when i tried to use a few mutations sequentially like that:

const firstMutationAtom = atomWithMutation(() => {
  return {
    mutationKey: ['firstMutation'],
    mutationFn: () => {
      return new Promise((resolve) => setTimeout(() => resolve('async result'), 1000));
    },
  };
});

const secondMutationAtom = atomWithMutation((get) => {
  const firstMutationResult = get(firstMutationAtom);
  return {
    mutationKey: ['secondMutation'],
    mutationFn: () => {
      if(!firstMutationResult?.data) {
        throw new Error('First mutation result is missing');
      }
      // continue with mutation
    },
  };
});

// usage
const { mutateAsync: firstMutateAsync } = useAtomValue(firstMutationAtom);
const { mutateAsync: secondMutateAsync } = useAtomValue(secondMutationAtom);

const runMutations = async () => {
  await firstMutateAsync();
  // some sync code
  await secondMutateAsync(); // fails because data in jotai is not updated yet
};

As i understand from atomWithMutation code, mutateAsync is returned directly from the tanstackQuery mutation, and updates to the jotai atoms are done using the observer.

That results in a behaviour, in which promise returned from mutateAsync resolves to the sync code of the function it was called in, and jotai won't be updated till all that code (including start of other mutations) will be executed.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions