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!

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

Simple JavaScript functions are used to check if a date is valid. function isValidDate(s) { var bits = s.split('/'); var d = new Date(bits[2] '/' bits[1] '/' bits[0]); return !!(d && (d.getMonth() 1) == bits[1] && d.getDate() == Number(bits[0])); } //test var

This article discusses how to use jQuery to obtain and set the inner margin and margin values of DOM elements, especially the specific locations of the outer margin and inner margins of the element. While it is possible to set the inner and outer margins of an element using CSS, getting accurate values can be tricky. // set up $("div.header").css("margin","10px"); $("div.header").css("padding","10px"); You might think this code is

This article explores ten exceptional jQuery tabs and accordions. The key difference between tabs and accordions lies in how their content panels are displayed and hidden. Let's delve into these ten examples. Related articles: 10 jQuery Tab Plugins

Discover ten exceptional jQuery plugins to elevate your website's dynamism and visual appeal! This curated collection offers diverse functionalities, from image animation to interactive galleries. Let's explore these powerful tools: Related Posts: 1

http-console is a Node module that gives you a command-line interface for executing HTTP commands. It’s great for debugging and seeing exactly what is going on with your HTTP requests, regardless of whether they’re made against a web server, web serv

This tutorial shows you how to integrate a custom Google Search API into your blog or website, offering a more refined search experience than standard WordPress theme search functions. It's surprisingly easy! You'll be able to restrict searches to y

The following jQuery code snippet can be used to add scrollbars when the div content exceeds the container element area. (No demonstration, please copy it directly to Firebug) //D = document //W = window //$ = jQuery var contentArea = $(this), wintop = contentArea.scrollTop(), docheight = $(D).height(), winheight = $(W).height(), divheight = $('#c


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

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

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver CS6
Visual web development tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software
