1. 14
    Migrate a Thunk in a Redux Application to an RTK Query Mutation
    1m 9s

Migrate a Thunk in a Redux Application to an RTK Query Mutation

Jamund Ferguson
InstructorJamund Ferguson
Share this video with your friends

Social Share Links

Send Tweet

Here we use builder.mutation() to define a mutation in our API. What is a mutation? Well it's basically a POST request or anything that would modify something on the server. You'll notice builder.mutation() and builder.query() look very similar except here we are passing the URL in an options object and that's only because we want to pass method and body as well. The query here could potentially also be a string just like in builder.query.

You probably noticed that we removed the refetch that was happening with dispatch(getDogs()). That will be replaced in the next lesson with the refetch method.

More information about the options you can pass into builder.mutation can be found here: https://redux-toolkit.js.org/rtk-query/usage/mutations

Instructor: [0:00] Open up apiSlice.js and add a new mutation for addDog. This one, the queries can take a body, turn an object. The url is going to be /dogs. The method will be post and it will return the body that we send in.

[0:18] Now, let's export useAddDogMutation and inside of DogsPage.jsx, let's import that new mutation. Here we can say const addDog equals useAddDogMutation. You can already see that we're starting to face a conflict with our previous addDog func that we were importing.

[0:38] Here, we call dispatch addDog and then we dispatch getDogs after that return successfully. For now, we're just going to replace all this with addDog data. We have our new addDog call here. We don't need a dispatch it, we just call it directly.

[0:52] Then we can remove our two func base calls from dog slice. If we go back to our My Dog's page, click Add Dog. We're going to add another one here. This is my dog, Milou. Refresh the page and you'll see he shows up right here.