Search code examples
reactjsapolloreact-apollo

Why react useQuery() doesnt fetch the newest data after a mutation?


I have a code like this

const [inputComment, setInputComment] = useState('');

const [
  commentPost,
  { data: data4, loading: loading4, errorCreate4 },
] = useMutation(COMMENT_POST);

const { error: error2, loading: loading2, data: data2 } = useQuery(
  GET_POST_BY_ID,
  {
    variables: {
      postid: item.id,
    },
  },
);

const doComment = () => {
  commentPost({
    variables: {
      postId: item.id,
      userEmail: email,
      comment: inputComment,
    },
  })
    .then(({ data }) => {
      setInputComment('');
      console.log('success');
    })
    .catch((e) => {
      console.log('not success');
    });
};

This is supposed to get the data, and when I do comment then it runs the mutation and re-render everything.

My problem is, it re-render alright BUT the data that the useQuery fetch is not the newest data a.k.a the data before I add a new comment.

Does anyone know how to fix this problem??

Please help :(


Solution

  • Your mutation modifies data on the server side.
    Once your mutation is done, you should refetch your data in order to get the modified version in your local cache on the client side.

    By guessing how your mutation and query actually work, here is how it would look like:

    const [
      commentPost,
      { data: data4, loading: loading4, errorCreate4 },
    ] = useMutation(COMMENT_POST, {
      refetchQueries: [
        { query: GET_POST_BY_ID, variables: { postid: item.id } }
      ]
    });
    

    Otherwise, intead of refetching from the server, you could update the local cache directly.
    More info can be found here in the official documentation.