Refactor baseQuery to use RTK Query fetchBaseQuery

Share this video with your friends

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.