Refactor baseQuery to use RTK Query fetchBaseQuery

Share this video with your friends

Social Share Links

Send Tweet
Published a year ago
Updated a year ago

There are a lot of edge cases that our simple fetch code is not handling. RTK Query has a great utility function called fetchBaseQuery that will execute a fetch and handle those annoying edge cases that you don't need to think through. We will refactor to use fetchBaseQuery with a "base url" and explore some new options like params and method we get as a result.

Instructor: [0:00] There are a lot of edge cases that this base query function currently is not handling. Also, it's something that we don't really need to write on our own. [0:10] RTK query already exports fetch base query function that we can use for this. Let's just swap it in here, and this already works. There is more that we can do.

[0:28] We can remove this here because as we see here and here, it's the same. Let's take that, and let's say, base URL is this string, and then we can also remove it down here.

[0:47] We can also go ahead and see that this, in the future, maybe should be more dynamic and we don't want to build a string for it, but we want to pass in the query parameters another way.

[1:01] Instead of returning this string, we can also return an object. The string is short notation, and we say URL is Pokémon. Then, we say params is limit nine.

[1:23] We keep this down here like it is, but let's just make it a arrow function so it's even shorter. In this notation up here, we could also add anything else that you would normally add to fetch.

[1:39] We could say method is get. This is already implied, and we could also put headers in here or whatever else.

egghead
egghead
~ 20 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