最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - react toastify clear or false when button click - Stack Overflow

programmeradmin1浏览0评论

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

      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

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./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

Share asked Mar 26, 2021 at 0:43 KumaraKumara 5283 gold badges13 silver badges39 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

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 })

      });

  }

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 ponent store object
    exampleAction() {
        this.addToast(() => {
            return toast.info('Click on the map to create a report.')
        });
    }
}
发布评论

评论列表(0)

  1. 暂无评论