React Redux Fetch and Load Data with RTK Query Tutorial

Redux is a powerful library for state management. The Redux centrally distributed store allows: components to access the state via store and update the React UI effortlessly.

In this post, we will understand how to work with RTK query, set up a Redux store, and create an API slice for fetching and caching the data in React.

To give you the context, we will create a simple user management app with the help of a fake REST API.

To get the data from the server: We’ll use createApi and fetchBaseQuery apis, and fetch the data from the server using RTK query.

How to Retrieve and Display Data in React with RTK Query

  • Step 1: Build React Project
  • Step 2: Install Redux Packages
  • Step 3: Create Api Slice
  • Step 4: Build Redux Store
  • Step 5: Show Fetch Results
  • Step 6: Update Global Component
  • Step 7: View App on Browser

Build 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-demo-app

Install Redux Packages

After you open the project folder, install the redux toolkit and bootstrap libraries.

npm install bootstrap react-redux @reduxjs/toolkit

“RTK Query is an advanced data fetching and caching tool, designed to simplify common cases for loading data in a web application.”

Create Api Slice

In the src folder, create features/dataSlice.js file, In this file:

We’ll import the createApi, and fetchBaseQuery modules.

These services allow us to create an endpoint that makes the request to the server and fetch the data using the builder query notation.

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

export const dataSlice = createApi({
  reducerPath: 'dataSlice',
  baseQuery: fetchBaseQuery({
    baseUrl: 'https://jsonplaceholder.typicode.com',
  }),
  endpoints: (builder) => ({
    getUsers: builder.query({
      query: () => '/users',
    }),
  }),
})

export const { useGetUsersQuery } = dataSlice

Build Redux Store

Building a Redux store is simple. Make the app/ folder with a store.js file, start importing configureStore, setupListeners, and dataSlice.

import { configureStore } from '@reduxjs/toolkit'
import { setupListeners } from '@reduxjs/toolkit/query'
import { dataSlice } from '../features/dataSlice'

export const store = configureStore({
  reducer: {
    [dataSlice.reducerPath]: dataSlice.reducer,
  },
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware().concat(dataSlice.middleware),
})

setupListeners(store.dispatch)

Head over to the src/index.js file; here, you must import ApiProvider and dataSlice, then wrap the App tag using ApiProvider.

import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'

import { ApiProvider } from '@reduxjs/toolkit/dist/query/react'
import { dataSlice } from './features/dataSlice'

const root = ReactDOM.createRoot(document.getElementById('root'))

root.render(
  <React.StrictMode>
    <ApiProvider api={dataSlice}>
      <App />
    </ApiProvider>
  </React.StrictMode>,
)

Show Fetch Results

Get inside the components/ folder, then create the Users.js file. Next, import the hook that we build using RTK query’s builder query notation..

import React from "react";
import { useGetUsersQuery } from "../features/dataSlice";

const Card = ({ data }) => {
  return (
    <div className="col-lg-12 mb-2" key={data.id}>
      <div className="card">
        <div className="card-body">
          <h5 className="card-title">{data.name}</h5>
          <p className="card-text">{data.username}</p>
        </div>
      </div>
    </div>
  );
};

function Users() {
  const { data, isLoading, isSuccess, isError, error } = useGetUsersQuery();

  let content;

  if (isLoading) {
    content = (
      <div className="d-flex justify-content-center">
        <div className="spinner-border">
          <span className="visually-hidden">Loading...</span>
        </div>
      </div>
    );
  } else if (isSuccess) {
    content = data.map((res) => {
      return <Card data={res} key={res.id} />;
    });
  } else if (isError) {
    content = <div className="alert alert-danger">{error}</div>;
  }

  return <div>{content}</div>;
}

export default Users;

Update Global Component

Lastly, we have to open the App.js file, here you have to import the component that we created to display the api response.

import '../node_modules/bootstrap/dist/css/bootstrap.min.css'
import Users from './components/Users'

function App() {
  return (
    <div className="container mt-5">
      <div className="row">
        <Users />
      </div>
    </div>
  )
}

export default App

View App on Browser

To check the API response, start the react app, and open the app on the browser with the given URL.

npm start
http://localhost:3000

React Redux Fetch and Load Data with RTK Query Tutorial

Summary

In this guide, we have learned how to use createSlice and fetchBaseQuery to create the API slice, get the data from the server through API and display the data using the React component.

Hence proved, Redux provides a handy way to fetch and cache data without writing excessive code for handling success, error or loading state for API requests.

Download full code of this tutorial from @GitHub.