Updating the Apollo cache

We want to explicitly add only the new post to the cache of the Apollo Client. Using the cache helps us to save data, by not refetching the complete feed or rerendering the complete list. To update the cache, you should remove the refetchQueries property. You can then introduce a new property, called update, as shown in the following code:

<Mutation
update = {(store, { data: { addPost } }) => {
const data = store.readQuery({ query: GET_POSTS });
data.posts.unshift(addPost);
store.writeQuery({ query: GET_POSTS, data });
}}

The new property runs when the GraphQL addPost mutation has finished. The first parameter that it receives is the store of the Apollo Client, in which the whole cache is saved. The second parameter is the returned response of our GraphQL API. 

Updating the cache works as follows:

  1. Use the store.readQuery function by passing a query as a parameter. It reads the data, which has been saved for this specific query inside of the cache. The data variable holds all of the posts that we have in our feed.
  2. Now that we have all of the posts in an array, we can add the missing post. Make sure that you know whether you need to prepend or append an item. In our example, we want to insert a post at the top of our list, so we need to prepend it. You can use the unshift JavaScript function to do this. We just set our addPost as the first item of the data.posts array.
  1. We need to save the changes back to the cache. The store.writeQuery.The function accepts the query which we used to send the request. This query is used to update the saved data in our cache. .second parameter is the data that should be saved.
  2. When the cache has been updated, our user interface reactively renders the changes.

In reality, you can do whatever you want in the update function, but we only use it to update the Apollo Client store.

We wait for the response to arrive, and then push the new item to the list afterward. In the next section, we will be a bit more optimistic about the response of our server, and will add the item before the request's response successfully arrives.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.33.41