Apollo Client is not refreshing data after mutation in NextJS?

Viewed 192

Here is the page to create a User

const [createType, { loading, data }] = useMutation(CREATE_USER_CLASS) //mutation query

const createUserClass = async (event) => {
    event.preventDefault();
    try {
      const { data } = await createType({
        variables: {
          userClassName,
        },
        refetchQueries: [{ query: STACKINFO }],
        options: {
          awaitRefetchQueries: true,
        },
      });
      setNotification({
        message: 'User class created successfully',
        code: 200,
      });

      handleClose();
    } catch (e) {
      setNotification({ message: e.message, code: 400 });
      handleClose();
    }
  };

The thing is I can see inside the network tab the API is calling twice, which is not a good way, but I can see the newly added data , but the page is not refreshing. Kindly help me

1 Answers

I was also struggling with a similar problem and I stepped into your question. I don't know which version of Apollo Client you are using, but I think that instead of using refetchQueries() method, you can try to use update() to clear the cache. This way you will notify UI of the change. Something like this:

createType({
    variables: {
      userClassName,
    },
    update(cache) {
       cache.modify({
          fields: {
           // Field you want to udpate
          },
       });
     },
  })

This is a link for reference from official documentation's page: https://www.apollographql.com/docs/react/data/mutations/#:~:text=12-,update

I hope it helps!

Related