In this article, we are going to learn how to make use of Redux Toolkit's RTK Query tool to make API calls, specifically, we are going to focus on making a GET Request API call. How I built a full stack real estate website coupled with aesthetic design using React/Tailwindcss with RTK Query to make multiple API Calls to different endpoints, and to different APIs from RapidAPI.
Introduction
Normally, web applications need to fetch data from a server in order to display it. They also usually need to make updates to that data, send those updates to the server, and keep the cached data on the client in sync with the data on the server. This is made more complicated by the need to implement other behaviors used in today's applications, such as:
- Tracking loading state in order to show UI spinners
- Avoiding duplicate requests for the same data
- Optimistic updates to make the UI feel faster
- Managing cache lifetimes as the user interacts with the UI
Over the last few years, the React community has come to realize that "data fetching and caching" is really a different set of concerns than "state management". While you can use a state management library like Redux to cache data, the use cases are different enough that it's worth using tools that are purpose-built for the data fetching use case.
This is where RTK Query comes to the rescue, as it is a powerful data fetching and caching tool. It is designed to simplify common cases for loading data in a web application, eliminating the need to hand-write data fetching & caching logic yourself.
We have seen the theory aspect of it, so, how can I use RTK Query in my application? Okay, let's see how it works in practical example.
Create an API Slice
For typical usage with React, we start by importing createApi and defining an "API slice" that lists the server's base URL and which endpoints we want to interact with:
import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";
In this example I will be making a GET request call to Bayut API, an API that query real estate in UAE, you can read more about it here
So, we first start by defining a service using a base URL and expected endpoints, for example;
export const bayutApi = createApi({
reducerPath: "bayutApi",
baseQuery: fetchBaseQuery({
baseUrl: "https://bayut.p.rapidapi.com",
prepareHeaders: (headers) => {
headers.set(
"X-RapidAPI-Key", ["insert private key"]
);
return headers;
},
}),
endpoints: (builder) => ({
getProperyDetails: builder.query({
query: (id) => `/properties/detail?externalID=${id}`,
}),
}),
});
// Export hooks for usage in functional components, which are
// auto-generated based on the defined endpoints
export const { useGetProperyDetailsQuery } = bayutApi;
Configure the Store
Next, we Configure the Store;
The "API slice" also contains an auto-generated Redux slice reducer and a custom middleware that manages subscription lifetimes. So, we need to add them to the Redux store:
import { configureStore } from '@reduxjs/toolkit'
// Or from '@reduxjs/toolkit/query/react'
import { bayutApi } from "./services/bayut";
export const store = configureStore({
reducer: {
// Add the generated reducer as a specific top-level slice
[bayutApi.reducerPath]: bayutApi.reducer,
},
// Adding the api middleware enables caching, invalidation, polling,
// and other useful features of `rtk-query`.
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(bayutApi.middleware),
})
Use Hooks in Components
So, how do we now get the data? Well, we import the auto-generated React hooks from the API slice into our component file, and call the hooks in our component with any needed parameters. RTK Query will automatically fetch data on mount, re-fetch when parameters change, provide {data, isFetching} values in the result, and re-render the component as those values change, in this case:
import { useGetProperyDetailsQuery } from './services/bayutApi'
export default function App() {
// Using a query hook automatically fetches data and returns query values
const { data, error, isLoading } = useGetProperyDetailsQuery('ID')
// render UI based on data and loading state
}
And if you follow the steps accurately, the returned data should be something like this;
Conclusion
That's it, we have just made a GET request call using Redux Toolkit's RTK Query, to Bayut API to fetch the property details. This was how I was able to build this Real Estate Application with numerous features, like Property Listing page, Property Details page, Agency List Page and many more.
It also features user authentication, which I used Firebase Auth REST API with Redux Toolkit's RTK Query, but this time I made a POST Request, unfortunately, the procedure is totally different and we will discuss this in my next article.
I hope you find value in this post, kindly leave a comment if you have any question, modification or addendum.