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
Published 2 years ago
Updated 2 years ago

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.

egghead
egghead
~ 33 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today