DEV Community

Michael Kienbusch
Michael Kienbusch

Posted on

Using Redux Toolkit (RTK) Query for API Fetch Requests

Introduction

As part of my final project for my web development course with Flatiron School, I decided to give the implementation of Redux Toolkit a try. I had thus far only manipulated state locally in React within specific components, but my instructor encouraged the students to step outside of their comfort zones and try new concepts with our final projects.

When working with React throughout the course, I had found it awfully repetitive sending fetch requests to my backend, converting the response to JSON, and then assigning that data to a local state variable using the useState hook. As I started looking into Redux, and the associated Redux Toolkit, I came across a powerful tool called RTK Query. It allows developers to fetch and cache data from API's with ease.

Note:

This demonstration is going to assume you have created a React application with npx create-react-app restaurant-app --template redux or npx create-react-app restaurant-app and afterwards installed Redux Toolkit with npm install @reduxjs/toolkit.

Step 1:

RTK Query is included with the core Redux Toolkit package. It is available to components within your application by using import { createApi } from '@reduxjs/toolkit/query/react'.

Step 2:

Define an "API slice", much like Redux slices, which will include the base URL you retrieve from the server as well as the endpoints you want to utilize from that base URL.

//./src/slices/restaurantSlice.js
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'


  //auto-generates an "API slice" when using createApi()
    //in this case, useGetAllRestaurantsQuery
export const restaurantApi = createApi({
    reducerPath: 'restaurantApi',
    baseQuery: fetchBaseQuery({ baseUrl: 'http://localhost:3000/'}),
    endpoints: (builder) => ({
        getAllRestaurants: builder.query({
            query: () => `/restaurants`,
        })
    }),
})

export const {useGetAllRestaurantsQuery} = restaurantApi
Enter fullscreen mode Exit fullscreen mode

Now useGetAllRestaurantsQuery is exported and set to retrieve from the http://localhost:3000/restaurantsendpoint. However, we still need to set up the Redux store.

Step 3:

To set up your Redux store, navigate to your "./src/store.js" file, and add the following code:

import { configureStore } from "@reduxjs/toolkit";
import { setupListeners } from "@reduxjs/toolkit/query";
import { restaurantApi } from "./slices/restaurantSlice";

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

})


export default store;
Enter fullscreen mode Exit fullscreen mode

Step 4:

Now you are all ready to import and use the React hook generated in Step 2, useGetAllRestaurantsQuery, in whatever component you need to.

import React from "react";
import { useGetAllRestaurantsQuery } from ".src/slices/restaurantSlice.js";

function Restaurants(){

    const { data, error, isLoading, isSuccess } = useGetAllRestaurantsQuery();

return(
    <div>{data.information}</div>
  )
}

export default Restaurants;
Enter fullscreen mode Exit fullscreen mode

The data, error, isLoading, and isSuccess state variables are provided by RTK Query, and can be used for custom handling of the response for different situations.

Other common usage:

You can add as many endpoints as you want, I only demonstrated one here. You can also search for specific items at an endpoint by adding parameters into the slice function and URL endpoint depending on how the API is structured:

getRestaurantByName: builder.query<Restaurant, string>({
      query: (name) => `restaurant/${name}`
Enter fullscreen mode Exit fullscreen mode

Conclusion:

Now your data is fetched and cached all with the use of one hook! I found RTK Query to be useful in the development of my project, and I hope you get a chance to use it too.

Top comments (0)