Redux Thunk

2019-06-13

What is Redux Thunk? It is a method to handle side-effects from performing asynchronous operations in Redux. Action in Redux does not allow asynchronous operations such as fetching data from an API. Thunk gives solution to this issue, it allows us to create an action that returns a function using dispatch

The way to implement thunk in Redux is by applying it inside the middleware, like so:

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

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

After that we can create an action such as:

function loginFormSubmitted(email, password) {
  return function (dispatch) {
    return validateLogin()
      .then((success) => dispatch(loginSuccess(email, password))
      .catch((error) => dispatch(loginFail(error)))
  }
}

By using thunk, we can perform an asynchronous task inside our action in redux. From the code above, if validateLogin function is successful, it will dispatch a loginSuccess function with email and password as the arguments. If it fails, it will dispatch a loginFail function.