Use Middleware to Handle Asynchronous Actions

Quick question regarding the following block of code:

const handleAsync = () => {
  return function(dispatch) {
    // Dispatch request action here
    dispatch(requestingData())
    setTimeout(function() {
      let data = {
        users: ['Jeff', 'William', 'Alice']
      }
      // Dispatch received data action here
    dispatch(receivedData(data))
    }, 2500);
  }
};

Specifically speaking to the dispatch which was passed into the function as a callback, and then used to dispatch dispatch(requestingData()) and dispatch(receivedData(data)) … Up until now I’ve been using store.dispatch() to send actions to the store and be run through the reducer…

My question is, why can we now use dispatch() it as it’s own function now? I’m assuming it’s something to do with Thunk or middleware… But I was having difficulty googling the exact answer online.

Thanks!

1 Like

The ability to use dispatch() as its own function is related to the concept of middleware in Redux, particularly Thunk middleware.
Middleware in Redux is like a layer that sits between dispatching an action and when it reaches the reducer. It allows you to perform asynchronous tasks, such as API calls, before the action reaches the reducer.
Thunk is a middleware that enables you to write action creators that return functions instead of plain action objects. These functions can perform asynchronous operations and then dispatch( )actual action objects when the operations are complete

I wrote this statement based on the knowledge I had and my understanding of your question. I hope you might understand something.!

Thanks man! I figured it was something to do with middleware that I could use dispatch() all on it’s own, and not have to use store.dispatch().

Thanks again for confirming that, I appreciate it! I wanted to make sure that I didn’t really miss something…

Thanks!
I should do yours. Your question gave me an opportunity to learn.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.