Calling Async Function in Action with Redux-Thunk

Redux-thunk is a simple middleware that enables you to call functions in redux action.

Thunk means function returning function. In JavaScript programming, we use thunk all the time although we may not use the name. Wikipedia has a simple example of thunk if you are interested. As the name suggests, redux-thunk is a thunk used as a middleware to inject the logic into action dispatching.

The use case is very simple. Use it when you want to call async function before dispatching the action. See the example below to retrieve the account information from a remote endpoint then update the store. Wouldn’t it be nice if we can do this in action?

By default, redux dispatch method only takes object. See the source code for the dispatch method below. The function above will cause error. It will tell you that only object can be dispatched and even tell you to use custom middleware for async action.

Redux-thunk is basically a custom middleware that allows function to be passed to dispatcher and get rid of the error that you get from the native dispatch function in redux.

Redux-thunk source code is famous for its brevity. Size does not matter here. It does the magic of bringing async functions into action.

This is the current redux-thunk source code.

Awesome, now you know what redux-thunk is and when to use it. It’s time to set it up

Setting up redux-thunk

Setting up is as easy as the module itself. All you need to do is to install the redux-thunk module and apply it as a middleware in the index file.

Installation

npm i –save redux-thunk

Index.js

Let’s start writing action with async functions. Here are some examples. The argument can be just dispatch or dispatch + getState or dispatch + getState + your custom arguments. This gives a lot of flexibility and can add cool logic to your action.

Action.js

Front-End
TypeScript: type aliases to check type equality

This post is to analyse how the type equality check by using type aliases proposed by Matt Pocock in his twitter post. These type aliases allow us to elegantly express type equality checks in unit tests. All we need to do is to pass the output and expected types in …

Front-End
Fixing it.only type error in Jest

If you are getting a type error with it.only in Jest, it could be due to incorrect TypeScript typings or incompatible versions of Jest and TypeScript. To resolve this issue, you can try the following steps: Make sure you have the latest versions of Jest and its TypeScript typings installed …

Front-End
yup conditional validation example

Here’s an example of a Yup validation logic where the first input field is optional but, if filled, it must contain only alphabetic characters, and the second input field is required: import * as Yup from “yup”; const validationSchema = Yup.object().shape({ firstField: Yup.string().matches(/^[A-Za-z]*$/, { message: “First field must contain only …