Kumara
Kumara

Reputation: 528

react toastify clear or false when button click

I am using react-toastify for my form. currently i show the message when error or success message. when user's click again i need to clear or hide all type of toast notifications. please check below code.

Used library for toast https://www.npmjs.com/package/react-toastify

      const addRecord= (form) => {
     toast.hide(); // i need to hide all toast notification 
    const header = {
      Auth_token: `${appUserConfig.accessTokenName}=${appUserConfig.accessToken}`,
      User_name: appUserConfig.userName,
    };
    httpPost(SAVE_INVOICE, data, header)
      .then((response) => {

        if (response.status === 200) {
          toast.success('Successfully Saved', { position: toast.POSITION.TOP_RIGHT })
        }

      })
      .catch((e) => {
        console.log("e:", e);
        toast.error('Something went wrong', { position: toast.POSITION.TOP_RIGHT, autoClose: false })

      });

  }

according to my requirement, I need to keep error message toast without autoClose. There fore when user click again add button i need to clear all toast notification. How i do this

Upvotes: 1

Views: 14265

Answers (2)

mdabrowski
mdabrowski

Reputation: 76

You can also make a queue cleanup if you used mobx. When we reach limit of toasts we clean the oldest one to make room for recently triggered one. Made it with React on Typescript, mobx and react-toastify. So whenever you use mobx you can consider appling something similar if needed.

import React, {ReactElement} from "react";
import {observer} from "mobx-react";
import {action, makeObservable, observable} from "mobx";
import {ToastContainer, Id as ToastId, toast} from "react-toastify";

export interface Props {
    store: Store
}

// observer is needed for Component to track changes in observables taht we have in store
export default observer(function MyComponent({store}: Props): ReactElement<Props> {
    return (
        <>
            <ToastContainer
                position="bottom-center"
                // we tie here limit variable from store
                limit={store.toastLimit}
                autoClose={false}
                hideProgressBar={true}
                newestOnTop={true}
                closeOnClick
                rtl={false}
                draggable
                theme="light"
            />
            <button onClick={() => {
                store.exampleAction();
            }}>Trigger our action</button>
        </>
    )
});

export class Store {
    // specify how many toasts you want to display
    toastLimit: number = 3;
    // we will hold toasts Ids here, the object itself is named Id, I change the name in imports
    displayedToasts: ToastId[] = [];

    constructor() {
        // standard mobx constructor, can be done automaticaly bu make auto observable
        makeObservable(this, {
            displayedToasts: observable,
            toastLimit: observable,
            removeOldestToast: action.bound,
            addToast: action.bound,
            exampleAction: action.bound
        })
    }
    
    // logic that will execute when we add new toast, we pass function to check if limit is reached, so thats why we use function parameter here
    addToast(toastFunc: () => ToastId) {
        if (this.displayedToasts.length === this.toastLimit) {
            this.removeOldestToast();
        }
        this.displayedToasts.push(toastFunc());
    }
   
   // if we reached limit we will need to remove oldest toast so we shift it from array and dismiss it from toast object
   removeOldestToast() {
        let shiftedId = this.displayedToasts.shift();
        if (shiftedId) {
            toast.dismiss(shiftedId);
        }
    }

    // usage of the toast logic above, you can allso call it from component store object
    exampleAction() {
        this.addToast(() => {
            return toast.info('Click on the map to create a report.')
        });
    }
}

Upvotes: 0

Yadab
Yadab

Reputation: 1883

You might want to check its documentation for clearing all the toast. Here is what i have found

Ref: https://fkhadra.github.io/react-toastify/remove-toast

To remove all the toast use:

toast.dismiss();

In your context do like this.

const addRecord= (form) => {
     toast.dismiss(); // i need to hide all toast notification 
    const header = {
      Auth_token: `${appUserConfig.accessTokenName}=${appUserConfig.accessToken}`,
      User_name: appUserConfig.userName,
    };
    httpPost(SAVE_INVOICE, data, header)
      .then((response) => {

        if (response.status === 200) {
          toast.success('Successfully Saved', { position: toast.POSITION.TOP_RIGHT })
        }

      })
      .catch((e) => {
        console.log("e:", e);
        toast.error('Something went wrong', { position: toast.POSITION.TOP_RIGHT, autoClose: false })

      });

  }

Upvotes: 7

Related Questions