1. 15
    Manually Refetch Data After an RTK Query Mutation with unwrap() and refetch()
    1m 44s

Manually Refetch Data After an RTK Query Mutation with unwrap() and refetch()

Jamund Ferguson
InstructorJamund Ferguson
Share this video with your friends

Social Share Links

Send Tweet

This lesson is about a powerful combo, refetch and unwrap.

The first and simplest concept is refetch, which forces whatever query you're subscribed to, to pull the latest data from the server. Refetch takes no arguments and doesn't let you change the query in any way. It just forces it to be called again. Another way to manually call refetch is to use initiate on your query's endpoint. For example, api.endpoints.getDogs.initiate(undefined, { forceRefetch: true }) would do the same thing as our refetch call here, but refetch is a lot cleaner.

The second part is around unwrap, which lets you access the original promise result from a mutation, which you can then use to immediately trigger some action, such as refresh. Or, you can use it to display an error message when the mutation fails.

Instructor: [0:00] Open up DogsPage.jsx and destructure the variable refetch off of usegetDogsQuery. Now down in handleNewDog, after addDog, type unwrap then and call refetch after that. Unwrap gives us access to the promise that's being used to fetch data over the network.

[0:16] When that comes back, we could potentially deal with the data directly or kick off an action like refetch, which in this case is going to refetch the list of dogs. We know we need to refetch then because we've just added a new dog. Up until this point, we haven't given RTK Query any other reason to think that we need to pull any new data.

[0:35] Let's take a look at how it works out. I'm on the My Dog's page, I click add dog, going to add a new dog called Lucy. When I click Add Dog, Lucy's updated automatically. I did not need to refresh the page like I used to before.

[0:48] Now there's one other thing that is really helpful for using unwrap and that's handling non-200 status codes and other errors that you might receive from a mutation.

[0:57] I'm going to add a catch here and we're going to clear the error response and then I'm going to type const message equals adding dog failed. In this case, just to see what all comes back. We're going to type JSON.stringify response. Below that, I will just alert the message.

[1:14] In a real application, please don't ever use alert. Very briefly here, I'm going to go into my addDog server handler and just have it return a message of too many dogs.

[1:24] Back in the web browser here, I'm going to add another dog called Martin. When I do, adding dog failed, status 500, data message too many dogs. Here you can see how we can use unwrap to either handle a successful outcome of a mutation or handle when a mutation fails.