How to Fetch API Data With RTK (Redux-Toolkit)

Written by Addo | Published 2022/01/14
Tech Story Tags: react-hook | redux | react-redux | hooks | redux-toolkit | front-end-development | fetch-api-data-with-rtk | learn-to-code

TLDRIn this article, I would like to refresh our knowledge about how to manipulate API data with the Redux Toolkit. First, we need API endpoints so we can make the GET request. Use any of the APIs from [RapidAPI]:https://rapidapi.com/. The next step is to connect the redux store to the React app. We will also need a `request` variable for the URL and the headers. Lastly, we create a custom hook to retrieve the data.via the TL;DR App

In this article, I would like to refresh our knowledge about how to manipulate API data with the Redux Toolkit.

First, let us install the following package:

npm i @reduxjs/toolkit

Next, we shall import the following in our app,

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
import { configureStore } from '@reduxjs/toolkit';

Awesome, next, we need the API endpoints so we can make the GET request. For this example, let us use any of the APIs from RapidAPI. This API has a URL and headers, so let us get them. We will create a variable for the URL and the headers.

const headers = {
  'x-rapidapi-host': 'coinranking1.p.rapidapi.com',
  'x-rapidapi-key': '799b9cc14emsh9f25bfec0439608p176b8cjsn760190b3e59c'
}

Now, let us get our endpoint,

const url = 'https://coinranking1.p.rapidapi.com';

We need to configure our store. So here is how we do it.

export default store({
  reducer: {
    [myApi.reducerPath]: myApi.reducer,
  },
});

Now the next step is to connect the redux store to the React app. Import ‘Provider’ from ‘react-redux’ and store. And pass the store variable as props to store.

<Provider store={store}>
  <App />
</Provider>

Now that we have our URL and headers, let us start creating and fetching data. We will also need a requestvariable so we can have the url and headers in them. Like the example below:

const createRequest = (url) => ({ url, headers });

So this variable is taking in the url as arguments and returning the url with the headers. That is why we created the variable createRequest. Awesome

Now is the time to use the createApi method from the @reduxjs/toolkit/query/react.

const myApi = createApi({
  reducerPath: 'cryptoApi',
  baseQuery: fetchBaseQuery({ url }),
  endpoints: builder.query({
    getCryptos: builder.query({
      query: (count) => createRequest(`/coins?limit=${count}`),
    }),
  })
});

Now, we have our API endpoint. We need to get a method to query API endpoints. Now is time to create our custom hook

export const { useGetCryptosQuery } = myApi;

Now we have created a function/hook to access the getCryptos variable result from the API.

Remember the naming conventions of a hook, but in this case, we use the use GetCryptos Query . So we prepend the “use” and append “Query” to the “GetCryptos.”

Here is how we use this hook to retrieve data:

const { data: cryptosList, isFetching } = useGetCryptosQuery(count);

Here, we are renaming the data variable to cryptoList, meanwhile, we have access to the isFetching variable. So that we can implement a loading functionality when data is not yet ready/available. We are passing in the count variable to keep track of the number of cryptos.

We can simply access the cryptos by console.log(cryptosList), where we can see the whole list of data available to us.

I hope this explanation is useful to us. For more clarity. You can visit this link.

If you like and understand this tutorial, kindly like and share. Thanks


Written by Addo | Full-Stack Web Developer
Published by HackerNoon on 2022/01/14