[Redux] Async in Redux: react-thunk

In most production webs, the data come from the remote services. So you cannot get the data right away. There are a couple of ways to handle async operations in Redux such as “redux-saga”, “redux-promise”, etc. “redux-thunk” is simple and effective for most scenarios.

 

1. redux-thunk

A thunk is a computer science term. It is a function that wraps an expression in order to delay its evaluation.

redux-thunk allows you to write action creators (functions to create actions) that returns a function instead of an action and then you can execute the dispatch() later.

 

2. Setup Thunk

redux-thunk is a middleware in Redux.

import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers/index';

const store = createStore(
  rootReducer,
  applyMiddleware(thunk)
);

 

3. Structure of redux-thunk

The main idea of the redux-thunk is you can return a function in action creators. This inner function can have 2 parameters (dispatch and getState) that are from the Redux store.

const action1 = (data) => {
  return {
    type: 'myAction',
    data
  };
};

const asyncAction1 = () => {
  return (dispatch, getState) => {
    dispatch(...);
  };
}

 

4. Async Operation with Thunk

The most common usage of the “redux-thunk” is async actions.

const asyncLoad = () => {
  return (dispatch) => {
    return apis.loadData().then( data =>
      dispatch({
        type: 'load',
        data
      });
    )).catch(error => { ... });
  };
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s