Updating the UI with the Apollo Client

After running the addPost mutation, the request goes through to the server and saves the new post in our database without any problems. However, we still cannot see the changes take effect in the front end immediately.

In this introduction to direct cache access and refetching, we will focus on the new standard Query and Mutation components. If you, like me, prefer HoCs, there are many tutorials that cover how to update the UI when using HoCs. 

There are two different ways to update the UI after a mutation:

  • Refetching the dataset: This is easy to implement, but it refetches all of the data, which is inefficient.
  • Updating the cache according to the inserted data: This is harder to understand and implement, but it attaches the new data to the cache of the Apollo Client, so no refetching is needed.

We use these solutions in different scenarios. Let's take a look at some examples. Refetching makes sense if further logic is implemented on the server, which is hidden from the client when requesting a list of items, and which is not applied when inserting only one item. In these cases, the client cannot simulate the state of the typical response of a server.

Updating the cache, however, makes sense when adding or updating items in a list, like our post feed. The client can insert the new post at the top of the feed.

We will start by simply refetching requests, and then we'll go over the cache update implementation. The following sections (and chapters) will assume that you are not using the HoC method.

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

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