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:
- It forces you to duplicate this logic wherever you want to show the notification.
- If it is fast enough to display two notifications, those notifications will not have IDs, so a race condition will occur. When the first timeout expires, it incorrectly dispatches a HIDE_NOTIFICATION, prematurely hiding the second notification.
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...
