In this lesson, you will learn how to update the Apollo Link State cache using a mutation.
Instructor: [00:00] Instead of writing directly to the cache, what we can do is abstract this and put it into a mutation. We can do this by adding a resolver to our client state. I'm going to say, "resolvers." Inside that, we want to add a mutation.
[00:14] We want to give this a name. I'm going to call mine "increment." This is going to be a function. We don't care about the first two parameters for now. The last parameter, we want to grab the cache. With that, we can have access to the data and write data.
[00:30] We want to start off by getting the current count. We can get this by saying, "cache.readQuery." We're going to say, "query" and then specify the query that we want to read. We want to read this query right here, so I'm going to move it to the top. That way, we can access it. Right here, I can say, "get countQuery."
[00:50] What I want to do now is write to the query and increment the count, so pretty much what we have right here. We can use that same thing, but instead of client, we're going to say, "cache." To increment the count, the current count is right here. I'm going to say, "currentCount." Then we're just going to add one to it. I'm going to say, "return null."
[01:16] We can actually call this mutation down here, on our button. We are going to start by saying "const incrementMutation" and creating the actual mutation that we want. I'm going to say, "mutation." Inside of this, I'm going to say, "increment."
[01:36] I want to say this is a client. I'm going to decorate it with a client decorator. That way, it knows we're doing a local mutation. I can use the mutation component from React Apollo. I can now wrap my button in that.
[01:54] Then I'm going to turn this into a function. Here, we're going to say, "increment." We need to actually specify the mutation that we want to pass in, which is the one we created right here, called "incrementMutation."
[02:10] We have this mutation that we can call. I'm just going to pass that to onClick. I can click on the button to call on the mutation and update the cache.