React 18 Fetch Data with Redux Toolkit RTK Query Tutorial

Last Updated on by in React JS

React Redux used together, React Redux enables seamless state management in React applications, offering a centralized store for state and enabling components to access and modify state data.

In this comprehensive tutorial, we will learn how to retrieve REST API data in React function component using Redux toolkit, RTK Query and RTK query hooks.

Redux is state management library, serves as a global store, retains the complete state of the application at a centralized location, React components can subscribe to this store to receive updates when the state changes. This library offers dynamic, intuitive methods that efficiently handles data manipulatin in combination with api slice, createApi, and fetchBaseQuery services.

RTK query makes the data loading faster in web applications, an additional addon that comes with the Redux Toolkit. Offering createApi API, including createApi(), fetchBaseQuery(), ApiProvider and setupListeners().

Let’s dive into the process of creating the redux store, API slice, and retrieving data with React Toolkit, RTK query using React function component.

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 --legacy-peer-deps

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.