1 year ago

#371332

test-img

arya.s

Toast Error message is shown multiple times in React/Redux. How to avoid it?

Using hooks generated by RTK query to bind response from backend as shown below.

const { data, error } = useApiQuery();

Code to generate rtk query hooks

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

export interface TestObject {
    //some feilds
}

export const testApi = createApi({
    reducerPath: "testApi",
    baseQuery: fetchBaseQuery({ baseUrl: "http://localhost:3000/" }),
    tagTypes: ['Test'],
    endpoints: (builder) => ({
        api: builder.query<TestObject[], any>({
            query: () => `/testapi`,
            providesTags: ['Test']
        })
       
    })
});

export const { useApiQuery } = testApi; 

Using error object from rtk query response to show a toast notification like below.

export const App = () => {
    return (
    <>
        {error && openNotification(error)}
        //some code
    </>
   )
}

Open Notication implemention is as below.

import { notification } from 'antd';

export const openNotification = (errorObj: any) => {
  if (errorObj) {
    notification.open({
      message: 'Exception Occured',
      description: errorObj.message,
    });
  }
};

Here issue is toast message is getting showed multiple times as the error object will not get emptied. How can I avoid that ?

reactjs

react-redux

react-hooks

toast

rtk-query

0 Answers

Your Answer

Accepted video resources