paint-brush
How to Fetch API Data With RTK (Redux-Toolkit)by@Addo
5,546 reads
5,546 reads

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

by DanielJanuary 14th, 2022
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

In 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.

Company Mentioned

Mention Thumbnail
featured image - How to Fetch API Data With RTK (Redux-Toolkit)
Daniel HackerNoon profile picture


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