Friday, August 14, 2020

Adding Redux Thunk Middleware to a React-Redux App

In the previous post we saw about Redux Thunk middleware and its need, in this post we shall see on how to setup the redux-thunk middleware in a React Redux application. Assuming that we have a working React Redux application we shall see on how to add redux-thunk middleware to it.

To start with we need to install the redux-thunk middleware npm package.

npm install --save redux-thunk

Next we need to add the middleware in the createStore method as follows.

import { combineReducers, createStore, applyMiddleware  } from 'redux';
import { homeReducer } from './homeReducer';
import { listReducer } from './listReducer';
import thunk from 'redux-thunk';

const rootReducer = combineReducers({
    homeReducer,
    listReducer
  })

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

Since we are planning to make asynchronous API calls we will install the axios npm pakage which will help us to make the async calls.

npm install axios --save

Next we will have to create a thunk Action function which will make the axios API call and dispatch the actual action with the response from the axios API call, the thunk action looks as follows.

import axios from 'axios';
import * as appConfig from '../config';
import { GetLocations } from './actions';

export function FetchLocations() {
  const url = `${appConfig.LOCATION_API_URL}/GetAll`;
  console.log(url);
  return dispatch => {
    return axios.get(url)
      .then(res => res.data)
      .then(data => {
        console.log(data);
        dispatch(GetLocations(data));
        return data;
      })
  };
}

We have got all the pieces to integrate redux thunk with our react-redux application, we need to connect the pieces to get the async action working. From the react component we will call the new thunk action function instead of the actual action, thunk will make the async API call wait for the response and then trigger the actual action with the response from the API.

In the next post we will see a fully integrated working model of redux-thunk with an async API call.



Search Flipkart Products:
Flipkart.com

No comments: