7

I've searched around the internet for a solution on this issue and have not come across one yet. I am creating a new post and adding it to the Apollo root query cache. for some reason even though newData returns a new object with the new query, it does not get assigned to the cache.

    const [createPost, { error }] = useMutation(CREATE_POST_MUTATION, {
    variables: values,
    update(proxy, result) {
      const data = proxy.readQuery({
        query: FETCH_POSTS_QUERY,
      });

      let newData = [...data.getPosts];
      newData = [result.data.createPost, ...newData];
      proxy.writeQuery({ query: FETCH_POSTS_QUERY, data: newData });
      values.body = '';
    },
  });

2 Answers 2

13

After just a bit of posting this question, I figured it out. Looking over the apollo writeQuery docs I noticed that you must make a copy of each state.

const [createPost, { error }] = useMutation(CREATE_POST_MUTATION, {
    variables: values,
    update(proxy, result) {
      const data = proxy.readQuery({
        query: FETCH_POSTS_QUERY,
      });

      let newData = [...data.getPosts];
      newData = [result.data.createPost, ...newData];
      proxy.writeQuery({
        query: FETCH_POSTS_QUERY,
        data: {
          ...data,
          getPosts: {
            newData,
          },
        },
      });
      values.body = '';
    },
  });
0
7

you can do this :

  const [createPost, { error }] = useMutation(CREATE_POST, {
    variables: formValues,
    update(proxy, result) {
      const data = proxy.readQuery({
        query: FETCH_POSTS_QUERY,
      });
      proxy.writeQuery({
        query: FETCH_POSTS_QUERY,
        data: {
          getPosts: [result.data.createPost, ...data.getPosts],
        },
      });
      formValues.body = "";
    },
  });
2
  • I like this less verbose implementation better
    – Alkari
    Oct 8, 2021 at 9:55
  • Thank you, marking this as best solution. Oct 20, 2021 at 23:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.