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

How to Dispatch Redux Actions with Timeouts?

Linda Hamilton
Release: 2024-12-06 20:10:17
Original
625 people have browsed it

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);
Copy after login

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);
}
Copy after login

Then use it in components:

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

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);
  };
}
Copy after login

You can then dispatch the thunk action creator directly:

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

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

    // ...
  };
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template