Home >Web Front-end >JS Tutorial >How to Dispatch a Redux Action with a Timeout?
How to send Redux action with timeout?
Problem:
I need to update the notification status of my app using a timeout mechanism. Notifications are usually errors or messages. I need to send another action after 5 seconds to return the notification state to the initial state so that the notification is not shown. The main reason is to provide a feature where notifications automatically disappear after 5 seconds.
I have tried using setTimeout and returning another action, but without success, and I have not found any related methods online. I'm willing to try any suggestions.
Answer:
You don’t have to be limited to the habit of writing all operations into a function library. If you want to use timeouts in JavaScript, just use setTimeout. The same principle applies to Redux actions.
Redux does provide alternatives for handling asynchronous events, but you should only use these if you find that there is too much duplication of code. Unless you encounter such a problem, just use the options provided by the language and pursue the simplest solution.
Write asynchronous code inline
This is the easiest way. No Redux-specific methods are used here.
store.dispatch({ type: 'SHOW_NOTIFICATION', text: 'You logged in.' }) setTimeout(() => { store.dispatch({ type: 'HIDE_NOTIFICATION' }) }, 5000)
The same operation is done in the connected component:
this.props.dispatch({ type: 'SHOW_NOTIFICATION', text: 'You logged in.' }) setTimeout(() => { this.props.dispatch({ type: 'HIDE_NOTIFICATION' }) }, 5000)
The only difference is that the store itself is usually not accessible in the connected component, but is obtained by injecting props to dispatch() or Specific action creator. But for us, it makes no difference.
If you don't want to make typos when sending the same action in different components, you can extract the action creator instead of sending the action object inline:
// actions.js export function showNotification(text) { return { type: 'SHOW_NOTIFICATION', text } } export function hideNotification() { return { type: 'HIDE_NOTIFICATION' } } // component.js import { showNotification, hideNotification } from '../actions' this.props.dispatch(showNotification('You just logged in.')) setTimeout(() => { this.props.dispatch(hideNotification()) }, 5000)
Or, if you before They have been bound via connect():
this.props.showNotification('You just logged in.') setTimeout(() => { this.props.hideNotification() }, 5000)
So far we haven't used any middleware or other advanced concepts.
Extract the async action creator
The above method works well in simple cases, but you may find some issues with it:
To solve these problems, you need to extract a function, centralize the timeout logic and dispatch these two operations. As shown below:
// actions.js function showNotification(id, text) { return { type: 'SHOW_NOTIFICATION', id, text } } function hideNotification(id) { return { type: 'HIDE_NOTIFICATION', id } } let nextNotificationId = 0 export function showNotificationWithTimeout(dispatch, text) { // 为通知分配 ID,这样 reducer 就可以忽略不当前可见通知的 HIDE_NOTIFICATION。 // 或者,我们可以存储超时 ID 并调用 clearTimeout(),但是我们仍然需要在一个地方执行此操作。 const id = nextNotificationId++ dispatch(showNotification(id, text)) setTimeout(() => { dispatch(hideNotification(id)) }, 5000) }
Now the component can display notifications using showNotificationWithTimeout without having to repeat this logic or have race conditions with different notifications:
// component.js showNotificationWithTimeout(this.props.dispatch, 'You just logged in.') // otherComponent.js showNotificationWithTimeout(this.props.dispatch, 'You just logged out.')
showNotificationWithTimeout() Why accepts dispatch as The first parameter? Because it needs to send operations to the store. Components normally have access to dispatch, but since we want the external function to control the dispatch operation, we need to give control to it.
If you have exported a single store from a module, you can import it and do the send operation directly in it:
store.dispatch({ type: 'SHOW_NOTIFICATION', text: 'You logged in.' }) setTimeout(() => { store.dispatch({ type: 'HIDE_NOTIFICATION' }) }, 5000)
Looks simpler, but we do not recommend this Method . The main reason we don't like it is that it forces the store to be a singleton. This makes implementing server-side rendering very difficult. On the server side, you want each request to have its own store so that different users get different preloaded data.
A single store also makes testing more difficult. You can no longer mock a store when testing action creators because they refer to a specific real store exported from a specific module. You can't even reset its state externally.
So while you can technically export a single store from a module, we don't recommend doing so. Don't do this unless you're sure your app will never add server-side rendering.
Go back to the previous version:
this.props.dispatch({ type: 'SHOW_NOTIFICATION', text: 'You logged in.' }) setTimeout(() => { this.props.dispatch({ type: 'HIDE_NOTIFICATION' }) }, 5000)
This solves the problem of duplicate logic and avoids race conditions.
Thunk middleware
For simple applications, the above method is sufficient. If you're happy with that, don't worry about middleware.
In larger applications, however, you may find some inconveniences.
For example, passing dispatch around seems unfortunate. This makes it harder to decouple container and presentation components, since any component that sends Redux operations asynchronously as described above must accept dispatch as a prop so that it can be passed further. You can no longer use connect() to bind an action creator because showNotificationWithTimeout() is not really an action creator. It does not return Redux operations.
Also, it can be cumbersome to remember which functions are synchronous action creators (e.g. showNotification()) and which are asynchronous helper functions (e.g. showNotificationWithTimeout()). You have to use them in different ways and be careful not to confuse them with each other.
This is where we find a way to "legitimize" providing this pattern to helper functions and help Redux "treat" such async action creators as a special case of normal action creators rather than entirely Motivation for different functions.
If you still insist and think this problem exists in your own application, welcome to use Redux Thunk middleware.
Simply put, Redux Thunk teaches Redux to recognize special types of operations that are actually functions:
// actions.js export function showNotification(text) { return { type: 'SHOW_NOTIFICATION', text } } export function hideNotification() { return { type: 'HIDE_NOTIFICATION' } } // component.js import { showNotification, hideNotification } from '../actions' this.props.dispatch(showNotification('You just logged in.')) setTimeout(() => { this.props.dispatch(hideNotification()) }, 5000)
When this middleware is enabled, if you send a function, Redux Thunk middleware will pass dispatch to it as a parameter. It also "eats" such actions, so don't worry about your reducers receiving weird function arguments. Your reducers will only receive regular object operations—those sent directly, or as we just described, sent by functions.
Looks like it’s useless, doesn’t it? Not in this particular case. But it allows us to declare showNotificationWithTimeout() as a regular Redux action creator:
this.props.showNotification('You just logged in.') setTimeout(() => { this.props.hideNotification() }, 5000)
The above is the detailed content of How to Dispatch a Redux Action with a Timeout?. For more information, please follow other related articles on the PHP Chinese website!