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 | import { createStore, applyMiddleware } from "redux"; |
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 | import { createStore, applyMiddleware } from 'redux'; |
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 | import axios from "axios"; |
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