Redux Middleware

Redux Middleware

Middleware

Redux Middleware provides a third-party extension point between dispatching an action, and the moment it reaches the reducer.

redux-logger Middleware

redux-logger is a production Redux logging tool that lets you replay problems as if they happened in your own browser.

1
npm i redux-logger

To enable Logger Middleware, use applyMiddleware(...middleware) function to apply the middleware

1
2
3
4
5
6
7
8
import { createStore, applyMiddleware } from "redux";
import rootReducer from './reducers/index';
import logger from "redux-logger";

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

with the logger middleware, you will be able to see the redux state change from the console.

redux-thunk Middleware

A thunk is a function that returns another function.

redux-thunk middleware allows you to write action creators that return a function instead of an action. The primiary use case of redux-thunk is to send HTTP Request.

Installation

1
npm install redux-thunk

To enable Redux Thunk

1
2
3
4
5
6
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers/index';

// Note: this API requires redux@>=3.1.0
const store = createStore(rootReducer, applyMiddleware(thunk));

Async Action using redux-thunk

By default Redux’s actions are dispatched synchronously. This cause problem for non-trivial applications that needs to communicate with external APIs to perform side effect.

Thunk is a programming concept where a function is used to delay the evaluation/calculation of an operation.

Redux Thunk is a middleware that lets you call action creators that return a function instead of an action object. That function receives the store’s dispatch method, which is then used to dispatch regular synchronous actions inside the function’s body once the asynchronous operations have been completed.

The most common use case for Redux Thunk is for communicating asynchronously with an external API to retrieve or save data. Redux Thunk makes it easy to dispatch actions that follow the lifecycle of a request to an external API.

Install redux-thunk

1
npm install redux-thunk

actions/index.js - here we define a action creator - getTodo function returns a function instead of an object. The function takes a dispatch as parameter and dispatch object when async action completes.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import axios from "axios";

export const getTodo = id => {
return dispatch => {
dispatch(getTodoStarted());
axios
.get(`https://jsonplaceholder.typicode.com/todos/${id}`)
.then(res => {
dispatch(getTodoSuccess(res.data));
})
.catch(err => {
dispatch(getTodoFailure(err.message));
});
};
};

const getTodoStarted = () => ({
type: "GET_TODO_STARTED"
});

const getTodoSuccess = todo => ({
type: "GET_TODO_SUCCESS",
payload: {
...todo
}
});

const getTodoFailure = error => ({
type: "GET_TODO_FAILURE",
payload: {
error
}
});

From the component, we can dispatch a function instead of an Object

1
dispatch(getTodo(id))

Here is the complete example that uses async action to fetch data

Reference