React Fetch Data with Redux Toolkit RTK Query Tutorial

Last updated on: by Digamber

In this comprehensive tutorial, we will cover how to retrieve data through REST API in React application using Redux toolkit library’s RTK Query and RTK query hooks.

If you have been working with React for a while, you must have heard the terms Redux and Redux Toolkit before. But what does the redux and redux toolkit do?

In this beginner-friendly tutorial, we are not just going to answer about these terms but also show you an advanced technique through which you can quickly handle data fetching with api slice using createApi, and fetchBaseQuery modules.

Redux is a popular predictable state container developed to assist you in building JavaScript apps that act consistently across client, server, and native environments and are super easy to test.

Whereas, Redux Toolkit or RTK is a handy library that offers valuable options to set up the global store and let you create actions and reducers in a more consistent way.

Redux Toolkit offers RTK Query, which makes data fetching and caching super easy and efficient. It is created to simplify common cases of data loading in web applications, and it is an additional addon that comes with the Redux Toolkit library.

RTK query can be invoked in React redux apps using createApi module, it offers createApi(), fetchBaseQuery(), ApiProvider and setupListeners(). This guide will show you how to create an API slice and register into the main redux store. Not just that, we will also show you how to use auto-generated React hooks created from the API slice in react component file.

React Redux Retrieve Data with RTK Query and API Slice Example

  • Step 1: Create React Project
  • Step 2: Install Required Libraries
  • Step 3: Retrieve Data with Query Endpoints
  • Step 4: Connect Api Slice to Redux Store
  • Step 5: Add API Provider and API Slice
  • Step 6: Display Data with RTK Hooks
  • Step 7: Register Component in App
  • Step 8: Run React Application

Create React Project

Now that you are familiar with what we are going to build, type the suggested command and install the new React project.

npx create-react-app react-rtk-query-example

As soon as the project is ready, use the command to jump into the project.

cd react-rtk-query-example

Install Required Libraries

Later in this post, we will create a redux store and write RTK queries to get the data using the endpoint api.

Hence, we need a couple of packages such as React-Redux, Redux Toolkit, and Bootstrap.

npm install react-redux @reduxjs/toolkit bootstrap

Retrieve Data with Query Endpoints

Create the ‘features’ folder in the ‘src’ directory, create the ‘features/api’ folder, and create the api file named features/api/apiSlice.js, then add the given code to the file.

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
export const apiSlice = createApi({
  reducerPath: 'apiSlice',
  baseQuery: fetchBaseQuery({
    baseUrl: 'https://jsonplaceholder.typicode.com',
  }),
  tagTypes: ['Post'],
  endpoints: (builder) => ({
    getPosts: builder.query({
      query: () => '/posts',
    }),
  }),
})
export const { useGetPostsQuery } = apiSlice

Import the createApi, and fetchBaseQuery modules from ‘@reduxjs/toolkit/query/react’ package.

The apiSlice should be used with one api slice per base URL in React project; it is a recommended way of creating api slice. Define the baseUrl using fetchBaseQuery, then write the getPosts query using the builder and query properties.

Connect Api Slice to Redux Store

Now, we will show you how to register apiSlice using setupListeners and configureStore modules.

Create the src/app/ folder then create the store.js file and add the code to the file.

import { configureStore } from '@reduxjs/toolkit'
import { setupListeners } from '@reduxjs/toolkit/query'
import { apiSlice } from '../features/api/apiSlice'
export const store = configureStore({
  reducer: {
    [apiSlice.reducerPath]: apiSlice.reducer,
  },
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware().concat(apiSlice.middleware),
})
setupListeners(store.dispatch)

Add API Provider and API Slice

Open the index.js file that is located in the src/ folder, around the App component define the ApiProvider and pass apiSlice to api property.

import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
import { ApiProvider } from '@reduxjs/toolkit/dist/query/react'
import { apiSlice } from './features/api/apiSlice'
const root = ReactDOM.createRoot(document.getElementById('root'))
root.render(
  <React.StrictMode>
    <ApiProvider api={apiSlice}>
      <App />
    </ApiProvider>
  </React.StrictMode>,
)

Display Data with RTK Hooks

Next, you have to create the features/posts/PostsList.js file. In this file, we are going to retrieve the store data and display via the component using useDispatch, useSelector and getUsers slice.

import React from 'react'
import { useGetPostsQuery } from '../api/apiSlice'
const PostCard = ({ content }) => {
  return (
    <div className="col-lg-12 mb-3 " key={content.id}>
      <div className="card">
        <div className="card-body">
          <h5 className="card-title">{content.title}</h5>
          <p className="card-text">{content.body}</p>
        </div>
      </div>
    </div>
  )
}
function PostsList() {
  const {
    data: posts,
    isLoading,
    isSuccess,
    isError,
    error,
  } = useGetPostsQuery()
  let postContent
  if (isLoading) {
    postContent = (
      <div className="d-flex justify-content-center">
        <div className="spinner-border" role="status">
          <span className="visually-hidden">Loading...</span>
        </div>
      </div>
    )
  } else if (isSuccess) {
    postContent = posts.map((item) => {
      return <PostCard content={item} key={item.id} />
    })
  } else if (isError) {
    postContent = (
      <div className="alert alert-danger" role="alert">
        {error}
      </div>
    )
  }
  return <div>{postContent}</div>
}
export default PostsList

In this section, we will build the frontend part of our app using the useGetPostsQuery hook that we build using apiSlice.

Start with importing the useGetPostsQuery hook; this hook provides data, isLoading, isSuccess, isError, or error properties.

These properties help us handle data fetching, loading, and error handling. Create the PostCard function, pass the content as props and define the HTML structure for showing the post data. Our next task is to define the conditional logic based on the useGetPosts query.

Register Component in App

We are now ready to register the PostsList component in the main component of React.

In order to add the component to the global component, add the below-mentioned code in the src/App.js file.

import '../node_modules/bootstrap/dist/css/bootstrap.min.css'
import './App.css'
import PostsList from './features/posts/PostsList'
function App() {
  return (
    <div className="container">
      <div className="d-flex border-bottom pt-2 pb-2 mb-5">
        <div className="p-2 flex-grow-1 text-center">
          <strong>React Redux Retreive Data with RTK Query Example</strong>
        </div>
      </div>
      <div className="row">
        <PostsList />
      </div>
    </div>
  )
}
export default App

Run React Application

Let us test this quintessential feature we just completed; here is the command which will initialize the react server and open the app on the browser simultaneously.

npm start
http://localhost:3000

React Fetch Data with Redux Toolkit RTK Query Tutorial

Conclusion

As the size and scope of the React app extend, it becomes cumbersome to manage the shared data. Redux library comes into play to reduce the pain of managing large React apps. Redux is known as a “predictable state container for JavaScript-based apps”.

It makes sure that React app works predictable and data sharing is even easier.

In this short tutorial, we learned how to build api slice in React js environment and make data fetching super easy with createApi, fetchBaseQuery modules and RTK query hooks.

Here is the GitRepo that you can download to comprehend the code with utmost precision.

Digamber

I am Digamber, a full-stack developer and fitness aficionado. I created this site to bestow my coding experience with newbie programmers. I love to write on JavaScript, ECMAScript, React, Angular, Vue, Laravel.