infinum / datx

DatX is an opinionated JS/TS data store. It features support for simple property definition, references to other models and first-class TypeScript support.
https://datx.dev
MIT License
140 stars 7 forks source link

mutate from useDatxInfinite doesn't work in useMutation #1174

Closed doroz0 closed 1 year ago

doroz0 commented 1 year ago

Used libraries

core, jsonapi, swr

Library version(s)

@datx/core 2.5.1, @datx/jsonapi 2.5.1, @datx/swr 2.5.1

Sample API response (if relevant)

No response

Environments with the issue

All

Environments without the issue

No response

Current behavior

  const getKey = (pageIndex: number, previousPageData: CollectionResponse | null) => {
    if (!showComments || (previousPageData && previousPageData.data.length === 0)) return null;
    return getPostComentsRelationshipPageQuery(post?.id, pageIndex + 1, 4);
  };

  const {
    data: comments,
    mutate: mutateComments,
    size,
    setSize,
  } = useDatxInfinite(getKey, {
    revalidateAll: true,
  });

  const [create, { status: createStatus }] = useMutation(createComment, {
    onSuccess: async () => {
      const input = inputRef.current;
      if (input) input.value = "";

      mutateComments(); // <--------
    },
  });

mutateComments in the onSuccess function doesn't work.

Expected behavior

mutateComments in the onSuccess function works

Reproduction steps

You can try it out at https://github.com/doroz0/soc-net-clone-nextjs, just remove the workaround (https://github.com/doroz0/soc-net-clone-nextjs/blob/main/src/components/Post.tsx#L144)
isBatak commented 1 year ago

It could be timing/scheduling related. I suspect in the order of dispatch and onSuccess call order. https://github.com/infinum/datx/blob/master/packages/datx-swr/src/hooks/useMutation.ts#L83-L88

useSWRMutation is doing similar thing but they use state instead of reducer. Is there any difference between those two 🤔. https://github.com/vercel/swr/blob/main/mutation/index.ts#L79-L80

The best thing would be to migrate to useSWRMutation completely, but this would be a breaking change.