My Learning Note on Redux (iii)

Image for post
Image for post
Photo by Olivia Colacicco on Unsplash

In the previous section we talked about basics about Redux and a simple use case to use React-Redux. In this post I’m going to share about Asynchronous Actions in Redux (impure actions).

So a common scenario will be fetching data — before, after (when succeed), after(when fail). In each of this state, we will have data , error , loading status updated.

So create the folder structure as below, and under each put:

Image for post
Image for post

There are a few points to note down here:

Async action creator:

Note that in the `fetchUsers function we returns a function instead of an object, this is because in store.js we have imported the redux-thunk middleware.

Using this specific middleware, an action creator can return a function instead of an action object.

When an action creator returns a function, that function will get executed by the Redux Thunk middleware. This function doesn’t need to be pure; it is thus allowed to have side effects, including executing asynchronous API calls. Middleware like thunk basically wraps the store’s dispatchmethod and allows you to dispatch something other than actions, for example, functions or Promises.

Note that there are 2 kinds of reducer:

  • Pure Reducer action: triggers a reducer and changes state.
  • Impure Async action: triggers an async action. This may call a Reducer action inside it.

Complex action payload:

We can do more complex stuff to action payload than we thought, instead of just taking some of it’s property, we can do things like :

data: users.data.children.map(child => child.data)

Middleware:

If you used express before, you might be familiar with middleware already. Redux middleware provides a third-party extension point between dispatching an action, and the moment it reaches the reducer. People use Redux middleware for logging, crash reporting, talking to an asynchronous API, routing, and more.

For our async actions, Thunk middleware isn’t the only way to orchestrate asynchronous actions in Redux:

And last but not least, if you are interested in how the UI integrates with our Redux part: below is the code for UserContainer.js :

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store