1. 9
    Update the local cache automatically when making mutations
    2m 17s

Update the local cache automatically when making mutations

Rares Matei
InstructorRares Matei
Share this video with your friends

Social Share Links

Send Tweet
Published 3 years ago
Updated 3 years ago

Understanding how Apollo normalises objects and how it stores them in the cache is especially helpful when writing our mutations. We'll see how just by making sure we return the ID of the changed entity from a mutation, plus any updated fields, Apollo will automatically make the necessary updates in the cache and re-render any components listening to that specific chunk of data.

Instructor: [0:00] We have a small issue. If I open up, let's say, the first note, and we make an update to it and press Save, the note will update on the backend, but this note here on the left, it still has the old text. That's not good.

[0:15] We learned in the previous lesson that any GraphQL objects coming back over the network are normalized and integrated into the Apollo cache. It happens that our backend is nice enough, it allows us to return the updated note from our mutation, and I can ask for the new and updated content.

[0:36] Because Apollo can't normalize an object without an ID, I'll need to return that as well. It's enough to just return the changed fields here. I don't need to return anything else, because as we saw in the previous lesson, Apollo takes any fields you give it and merges them in into existing objects in the cache.

[0:55] Now, I went ahead and reset my app. The first note is back to normal. If I make a change to it...and I'm going to press Save, but the keep an eye on this note here on the left. I'll press Save, it updates as well in real time.

[1:09] If we look at the network request, we can see that it's correctly returning us the changed fields, along with the ID of the note that was changed and the type name. Apollo is going to use the type name and the ID to determine what to update in the cache. Then, it's going to change the content field of that item.

[1:34] We can confirm this as well. If we open up the Apollo tab, go to the cache, and if we look at the first note, we can see that, yes, it has the edit, but then it also has the normal fields, like category. That hasn't disappeared. Apollo does all this work behind the scenes to normalize and structure your data, so that edits like this just work.

[1:57] It needs your help, though. You first need to make sure that your backend returns the changed object from your mutations. Then, you need to actually ask for those objects when you do the mutation, ensuring you add all the necessary changed fields. Then, you also include the ID, so that Apollo knows what to update.