Home >Web Front-end >JS Tutorial >How to Dispatch Redux Actions with Timeouts?

How to Dispatch Redux Actions with Timeouts?

Linda Hamilton
Linda HamiltonOriginal
2024-12-06 20:10:17667browse

How to Dispatch Redux Actions with Timeouts?

Dispatching Redux Actions with Timeouts

Problem

Suppose you have a Redux application that manages notifications, displaying messages like errors or informative alerts. You want to automatically dismiss these notifications after a certain time, say 5 seconds.

Solution: Inline Async Code

The simplest approach is to use setTimeout directly:

store.dispatch({ type: 'SHOW_NOTIFICATION', text: 'You logged in.' });
setTimeout(() => {
  store.dispatch({ type: 'HIDE_NOTIFICATION' });
}, 5000);

Solution: Extracting Async Action Creator

To avoid duplication and race conditions, consider extracting an action creator:

function showNotificationWithTimeout(dispatch, text) {
  const id = nextNotificationId++;
  dispatch(showNotification(id, text));

  setTimeout(() => {
    dispatch(hideNotification(id));
  }, 5000);
}

Then use it in components:

showNotificationWithTimeout(this.props.dispatch, 'You just logged in.');

Solution: Using Thunk Middleware

Thunk middleware provides more flexibility. It enables you to dispatch functions that return actions:

export function showNotificationWithTimeout(text) {
  return function (dispatch) {
    const id = nextNotificationId++;
    dispatch(showNotification(id, text));

    setTimeout(() => {
      dispatch(hideNotification(id));
    }, 5000);
  };
}

You can then dispatch the thunk action creator directly:

this.props.dispatch(showNotificationWithTimeout('You just logged in.'));

Reading State in Thunks

Thunks also allow you to read the current state of the store:

export function showNotificationWithTimeout(text) {
  return function (dispatch, getState) {
    if (!getState().areNotificationsEnabled) {
      return;
    }

    // ...
  };
}

Recommendations

Use the simplest approach that meets your needs. Thunks provide advanced async capabilities but may not be necessary in all cases.

The above is the detailed content of How to Dispatch Redux Actions with Timeouts?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn