0

Suppose I have the following GraphQL types:

type User {
  id: String!
  posts: [Post!]!
}

type Post {
  id: String!
  text: String,
}

And here is a mutation that returns the updated post:

mutation addNewPost(
  $userId: String!
  $text: String!
) {
  addNewPost(userId: $userId, text: $text) {
    id
    text
  }
}

After running this mutation my cache contains a new entry of a post. How do I add it to the user's posts array? I have tried cache.writeQuery and cache.modify but I cannot figure it out.

1
  • update after mutation is described in docs Commented Nov 26, 2020 at 23:06

2 Answers 2

7

We do push the item into array inside the update function, which is one of the options of useMutation. I'm writing the whole mutation so that you can get the idea 💡, let have a look at example:

By Update function:

const [createPost, { data, loading, error }] = useMutation(CREATE_POST, {
  update(cache, response) {

  // Here we write the update

  // Step 1: Read/Fetch the data   👈
  const data = client.readQuery({
    query: FETCH_POSTS_QUERY,
  });

  // Step 2: Update the cache by immutable way   👈
  client.writeQuery({
    query: FETCH_POSTS_QUERY,
    data: {
      getPosts: [response.data.createPost, ...data.getPosts],
    },
  });
 },
    variables: formValues,
  });

By refetchQueries:
That's really shortcut 🔥 way to update the cache, by using DocumentNode object parsed with the gql function

const [createPost, { data, loading, error }] = useMutation(CREATE_POST, {
   
    refetchQueries: [                         👈
               FETCH_POSTS_QUERY
              'fetchPosts`' // OR  Query name
   ],   
     
    variables: formValues,
  });
Sign up to request clarification or add additional context in comments.

2 Comments

Good answer :) deserves to be accepted.
Small typo, client should be cache.
0

You're going to want to directly write to the Apollo cache in order to update the other entities that your mutation has modified.

Have a look at the docs https://www.apollographql.com/docs/react/data/mutations/#making-all-other-cache-updates here for specifics (you're going to want to use cache.modify and cache.writeFragment)

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.