Redux - Asynchronous Actions
async actions
Why use Redux middleware?
Redux middleware can do anything when it sees a dispatched action: log something, modify the action, delay the action, make an async call, and more. Also, since middleware form a pipeline around the real store.dispatch function, this also means that we could actually pass something that isn’t a plain action object to dispatch, as long as a middleware intercepts that value and doesn’t let it reach the reducers.
Middleware also have access to dispatch and getState. That means you could write some async logic in a middleware, and still have the ability to interact with the Redux store by dispatching actions.
Consider the Redux Async Data Flow Diagram. Describe the flow in your own words. Differences between synchronous and asynchronous flow diagrams:
-
The middleware is handling the asynchronous part, responding to an action, perfroming an asynchrounous call and response cycle with an API.
-
Dispatch is used again after the middlware has done its asynchonous processing to update the action state.
How are we accommodating async in our Redux app?
I do not yet know how we are accomodating asynchronous dataflow iwithin our Redux application.
thunk middleware
Why would you need redux-thunk middleware? Redux is a state management tool, which is used to store the state of different variables in our react application. It makes complex react applications easier by centralizing the application state. Redux supports middleware, and middleware functions run between dispatching an action and the moment it reaches the reducer. Redux middlewares can be used for logging, routing, asynchronous actions, etc.
Thunk allows us to return functions instead of objects from redux actions. Plain redux doesn’t allow complex logic inside action functions, you can only perform simple synchronous updates by dispatching actions. This middleware extends its ability and lets you write complex logic that interacts with the store. Thunk doesn’t interfere with the action until it returns a function. Thunk allows us to dispatch actions manually, which gives us the power to incorporate some logic or run some asynchronous code before dispatching an action. The function returned from action is called a thunk function which is called with two arguments:
- dispatch: It is a method used to dispatch actions, that can be received by reducers.
- getState: It gives access to store inside the thunk function.
A thunk function may contain any arbitrary logic, sync, or async, and can call dispatch or getState at any time. Before moving any further let’s understand the difference between the flow of redux with and without thunk.
Redux Thunk middleware allows you to write action creators that return a ____ instead of an action. function
Describe how any return value from the inner thunk function will be made available.
Any return value from the inner function will be available as the return value of dispatch itself.