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.
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.!