Redux async logic and data fetching

WangYeUX
2 min readMar 4, 2021

--

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

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

WangYeUX
WangYeUX

Written by WangYeUX

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

No responses yet

Write a response