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.
The simplest approach is to use setTimeout directly:
store.dispatch({ type: 'SHOW_NOTIFICATION', text: 'You logged in.' }); setTimeout(() => { store.dispatch({ type: 'HIDE_NOTIFICATION' }); }, 5000);
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.');
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.'));
Thunks also allow you to read the current state of the store:
export function showNotificationWithTimeout(text) { return function (dispatch, getState) { if (!getState().areNotificationsEnabled) { return; } // ... }; }
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!