How to integrate RTK query with next js app

Reading Time: 3 minutes

Introduction

RTK Query is a powerful data fetching and caching tool. It is designed to simplify cases for loading data in a web application, eliminating the need to write extra code for data fetching and caching logic. Its functionality is similar to that of react queries, but it can be integrated directly with Redux. In this blog we will learn how to integrate rtk query with next js web app.

Create API using RTK Query

The core of rtk query functionality is createAPI(). First, we need to create a file called api.tsx, and let’s first import createAPI and fetchBaseQuery from the reduxjs/toolkit/query package.

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

const api = createApi({
  baseQuery: fetchBaseQuery({}),
});

Add baseUrl

Now we need to add an API with which we want to interact. We need to add the URL to fetchBaseQuery’s baseUrl. FetchBaseQuery is a small wrapper around the API that aims to simplify requests. We are going to use “https://jsonplaceholder.typicode.com” as the base url. Our resource server is called Photos, so we are changing the name from API to photosApi.

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

interface Photos {
  albumId: Number;
  id: Number;
  title: String;
  url: string;
  thumbnailUrl: string;
}

export const photosApi = createApi({
  baseQuery: fetchBaseQuery({
    baseUrl: "https://jsonplaceholder.typicode.com",
  }),

  endpoints: (builder) => ({
    photos: builder.query<Photos[], void>({
      query: () => "/photos",
    }),
  }),
});

export const { usePhotosQuery } = photosApi;

Now we can use this useContactQuery in our app component to fetch the data, but before we can do that, we have to bind this create API with our redux store. So, since we don’t have a store yet, let’s make one. 

Create Redux Store

First Let’s import the configure store from the Redux Toolkit and we have to also import the photosApi.

import { configureStore } from "@reduxjs/toolkit";
import { photosApi } from "../api/photosData";

export const store = configureStore({
    reducer: {
        // Add the generated reducer as a specific top-level slice
        [photosApi.reducerPath]: photosApi.reducer
    },
    // Adding the api middleware enables caching, invalidation, polling,
    // and other useful features of `rtk-query`.
    middleware: (getDefaultMiddleware) =>
        getDefaultMiddleware().concat(photosApi.middleware),
})

We haven’t created any reducer in our photosApi object, so how are we going to hook the reducer, Now we have to add one more property the reducer path.

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

interface Photos {
  albumId: Number;
  id: Number;
  title: String;
  url: string;
  thumbnailUrl: string;
}

export const photosApi = createApi({
  reducerPath: "photosApi",
  baseQuery: fetchBaseQuery({
    baseUrl: "https://jsonplaceholder.typicode.com",
  }),

  endpoints: (builder) => ({
    photos: builder.query<Photos[], void>({
      query: () => "/photos",
    }),
  }),
});

export const { usePhotosQuery } = photosApi;

Add Provider

Now, open the _app.tsx file and bind the app and add the provider there. We also need to import and pass the store.

import "../styles/globals.css";
import type { AppProps } from "next/app";
import { Provider } from "react-redux";
import { store } from "../store/store";

export default function App({ Component, pageProps }: AppProps) {
  return (
    <Provider store={store}>
      <Component {...pageProps} />
    </Provider>
  );
}

Data fetching using hooks

Now we are going to import the usePhotosQuery and this will be coming from the API file and usePhotosQuery exports a few more properties that we can use in our app. The properties will be data, isLoading and error which we are going to fetch from the server.

import React from "react";
import { usePhotosQuery } from "../../api/photosData";
import styles from "./Homepage.module.css";

function Homepage() {
  const { data, isLoading, error } = usePhotosQuery();

  let content = null;

  if (isLoading) {
    content = <div className={styles.loading}> Please wait ............ </div>;
  }

  if (error) {
    content = (
      <div className={styles.error}>
        {" "}
        Something went wrong, Please retry after some time{" "}
      </div>
    );
  }

  if (data) {
    content = (
      <>
        <h1 className={styles.heading}>List of Photos</h1>
        <div className={styles.main}>
          <ol className={styles.listSection}>
            {data?.map((data, index) => (
              <li key={index} className={styles.itemSection}>
                {data.title}{" "}
                <img className={styles["image-section"]} src={data.url} />
              </li>
            ))}
          </ol>
        </div>
      </>
    );
  }

  return <>{content}</>;
}

export default Homepage;

Conclusion

In this blog we learn how to integrate RTK query with next js web app but the more we will practice will give the clear idea of how it works, So keep Practicing. For more about it, refer here.

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading