RTK-Query-Redux-toolkit

How to Create React Apps With Redux Toolkit and RTK Query?

Introduction to RTK Query

  • It is a powerful server data fetching and caching tool. It’s designed to simplify the overall conditions for uploading data to a web application, eliminating the requirement for handwriting downloading data & the cache concept yourself.
  • A Query itself is created on top of the Redux Toolkit core.
  • It is included within the @reduxjs/toolkit package as an extra add-on.
  • That provides advanced setup options to handle your fetching and caching needs most flexibly and efficiently as possible.

RTK

Why RTK Query

  • As mentioned above, the main reason behind the RTK Query was to simplify the data fetching and caching process in React applications.
  • It allows you to trace the history of state changes over time.
  • Built with TypeScript, it’s first-class types support.
  • Support OpenAPI and GraphQL.
  • Support React Hooks.
  • It is added as middleware and provides powerful React Hooks to help fetch your data.
  • That is UI-agnostic. It will be integrated with any framework capable of using Redux (Vue.js, Svelte, Angular, etc. )

Hire Reactjs Developer

Fetching and Caching data with RTK Query

I suppose now you understand what RTK Query is and also the reasons behind its intro. Now we understand the fetch and cache data using RTK queries.

1. Data Fetching

RTK Query uses a method called fetchBaseQuery to fetch data from services. It is a lightweight fetch wrapper that handles request headers and responses rather than fetches and Axios.

service.js

import { createApi, fetchBaseQuery } from ‘@rtk-incubator/rtk-query’;

//Create your service using a base URL and expected endpoints
    export const demoApi = createApi({
      reducerPath: 'demoApi',
      baseQuery: fetchBaseQuery({ baseUrl: process.env.REACT_APP_API }),
      endpoints: (builder) => ({
      getRecords: builder.query({
        query: {( entity )} => {
        return {
          url: `demo/${entity}`,
          method: "GET",
          headers: {
          "content-type": "application/json;odata=verbose",
          },
        };
        },
      }),
      }),
    });

    export const { useGetRecordsQuery } = demoApi;

The next step is to add this service to our store by adding our generated reducer and our API middleware. This can activate caching, prefetching, polling, and other features.

store.js

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

Next, you would like to wrap the provider, as you’d do with a basic Redux store, then you’ll query in your components using your query hook.

index.js

import * as React from "react";
    import { useGetRecordsQuery } from "./services";

    export default function App(){
    //Using a query hook automatically fetches data and returns query values
    const { data: userRecoed, isError, isLoading } = useGetRecordsQuery("User");
    return (
      <div className="App">
        {isError ? (
          <>Oh no, there was an error</>
        ) : isLoading ? (
          <>isLoading...</>
    ) : userRecoed ? (
    <>
        <h3>{userRecoed.name}</h3>
        <h4>{userRecoed.email}</h4>
      </>
      ) : null}
    </div>
    );
    }

2. Data Caching

Caching is automatic in RTK Query. If your data ever changes, prefetching occurs automatically just for the elements that changed. This can be handled via RTK Query’s powerful queryCachedKey.

Conditional fetching

As mentioned above, useQuery automatically fetches your data and handles the caching.RTK Query provides a way to stop a query from automatically running with a boolean skip parameter which will be added to the query hook, which can help manage this behavior. Setting skip to false strongly affects the way your data is fetched and cached.

Mutation

Mutations are used to send data updates to the server and apply the changes to the local cache. Mutations can even invalidate cached data and force re-fetches.

addUserRecord: builder.mutation({
    query: params => ({
    url: `${params.entity}`,
    method: "POST",
    body: params.data,
    }),
    invalidatesTags: (result, error, arg) => (arg.tag ? [arg.tag] ? []),
    }),

Customizability

  • The complete client API library must be fully customizable; an honest example is Axios. This allows developers to possess the power to manage automated behavior, connectors, and authentication without the necessity to duplicate code.
  • createApi is the main point where the Query is going to be configured. It exposes parameters such as:
    • baseQuery, which can be customized from interceptors or mold return formats
    • endpoints, which is the set of operations you perform against your servers
    • setup listeners, which may be a utility to assist manage refetching either in an exceedingly global or granular way
    • Much more to handle your API calls and Redux store

Error handling

Errors are returned through the error property provided by the hook. A Query expects you to return payloads (errors or successes) during a particular format to help with type inference.

const { data: userRecoed, isError, isLoading } = useGetRecordsQuery("User");
      return (
        <div className="App">
          {isError ? (
            <>Oh no, there was an error</>
          ) : isLoading ? (
            <>isLoading...</>
          ) : userRecoed ? (
          <>
            <h3>{userRecoed.name}</h3>
            <h4>{userRecoed.email}</h4>
          </>
        ) : null}
        </div>
    );

Similarly Reference site: https://redux-toolkit.js.org

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply