close

How to dispatch a Redux action with a timeout?

Hello Guys, How are you all? Hope You all Are Fine. Today we are going to learn How to dispatch a Redux action with a timeout? in javascript. So Here I am Explain to you all the possible methods here.

Without wasting your time, Let’s start This Article.

How to dispatch a Redux action with a timeout ?

  1. How to dispatch a Redux action with a timeout ?

    to dispatch a Redux action with a timeout It is simple. Use trim-redux package and write like this in componentDidMount or other place and kill it in componentWillUnmount.

  2. How to dispatch a Redux action with a timeout ?

    to dispatch a Redux action with a timeout It is simple. Use trim-redux package and write like this in componentDidMount or other place and kill it in componentWillUnmount.

Method 1

It is simple. Use trim-redux package and write like this in componentDidMount or other place and kill it in componentWillUnmount.

componentDidMount() {
  this.tm = setTimeout(function() {
    setStore({ age: 20 });
  }, 3000);
}

componentWillUnmount() {
  clearTimeout(this.tm);
}

Method 2

This may be a bit off-topic but I want to share it here because I simply wanted to remove Alerts from state after a given timeout i.e. auto hiding alerts/notifications.

I ended up using setTimeout() within the <Alert /> component, so that it can then call and dispatch a REMOVE action on given id.

export function Alert(props: Props) {
  useEffect(() => {
    const timeoutID = setTimeout(() => {
      dispatchAction({
        type: REMOVE,
        payload: {
          id: id,
        },
      });
    }, timeout ?? 2000);
    return () => clearTimeout(timeoutID);
  }, []);
  return <AlertComponent {...props} />;
}

Summery

It’s all About this article. Hope all method helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you? Thank You.

Leave a Comment