Redux async logic and data fetching

Middleware, a extra step where async logics run.

Redux store itself don’t know anything about async logic. It only knows how to synchronously dispatch actions, update the state by calling the root reducer, and notify the ui which needs to be updated. Any asynchronicity happen outside the store.

Redux middleware, on the other side, allow you to using async logics to interact with the store. Middleware has access to dispatch and getState, which means you could write async functions in the middleware, and still has the ability to interact with the redux store by dispatching actions.

There are three concepts: the middleware, the async function and dispatch function. In sync logic, store dispatch a action. However, in the async logics, store dispatch a async function which wraps a normal dispatch.

The store dispatches a async function, which takes dispatch and getState as arguments. In the async function, it execute the async logics and then dispatch an action as same as the normal dispatch process. It is a bit convoluted, check the code below for a deeper understanding.

There are loads of middleware for redux, the most common one is redux-thunk. As redux docs states: The word “thunk” is a programming term that means “a piece of code that does some delayed work”. The thunk middleware allows us to write functions that get dispatch and getState as arguments. The thunk functions can have any async logic inside, and that logic can dispatch actions and read store state as needed.

In short, thunk function takes dispatch and getState as arguments. It processes async logics first, then dispatch a action with the data coming from the async logics. Let’s write some code to explains this process.

How redux thunk works. Reference: https://redux.js.org/tutorials/fundamentals/part-6-async-logic

A front-end developer who likes designing stuffs. Technical blog rookie. Loving sharing.