search
HomeWeb Front-endJS TutorialHow to Dispatch a Redux Action with a Timeout?

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!

Statement
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
JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MantisBT

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.