Set up RTK Query with createAPI and ApiProvider that Serve Fake Data

Share this video with your friends

Send Tweet
Published a year ago
Updated a year ago

The first thing we need to do to set up Redux Toolkit Query is to create API end points and wrap our application in an ApiProvider that RTK Query gives us. For this application, we will expose two endpoints. One endpoint will be the list of all pokemon and the other will be the pokemon detail page.

Then we'll use the endpoints we built and load the data from RTK Query hooks along with loading and error states.

Instructor: [0:00] The first thing we have to do is install Redux toolkit and react-redux. After that is done, we can import createAPI from reduxjs/toolkit/query/react. [0:26] Now, we can create our API. An API always needs the baseQuery, but we're not going to use it right now so I'm going to just use an empty function. We also need endpoints which are created with a build annotation.

[0:50] We are creating an object with our endpoints. The first of which is PokemonList which is a query with a query function that in our case just returns our fake data for the listing as data.

[1:14] We're also going to add a second endpoint which we are going to call PokemonDetail, but this one just returns the fakePokemonDetailData. This has internally created two hooks for us, which we can just extract from our API. One is called usePokemonListQuery and the other one is called usePokemonDetailQuery.

[1:44] You see this PokemonList goes in here and this PokemonDetail goes in here. We're going to use before and a query after. Before we can use this, we have to add an ApiProvider to our application which will internally create a Redux store and set everything up for us.

[2:09] We look into how to set up a Redux store normally another time. Now instead of using the fake data, we use data from the hook but we're not only using the data. This is now asynchronous so we can also use a loading state, an error state, and a success state. If we are loading, we want to return a loading message. If we are in an error state, we just return something went wrong. In our isSuccess case, we just continue rendering what you did before.

[3:02] Now, we take this and repeat essentially the same thing down in our PokemonDetails, but we don't want to use PokemonListQuery. We use PokemonDetailQuery here. We can now check this out and everything essentially looks like before.

[3:21] We don't see our loading state because this is just too fast so we have to make it a little bit slower. We create a function to simulateLoading and this returns a new Promise and resolves after a timeout of maybe 500 milliseconds. Now, we can go ahead and make our query function async and await simulateLoading.

[3:55] We do the same down here and if we jump over to the application and refresh, you see it's loading for a second. We go to Bulbasaur. It's loading and now, it's not loading anymore because it's already in the cache.