Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add multiple middleware to Redux?

I have one piece of middleware already plugged in, redux-thunk, and I'd like to add another, redux-logger.

How do I configure it so my app uses both pieces of middleware? I tried passing in an array of [ReduxThunk, logger] but that didn't work.

Code:

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import ReduxThunk from 'redux-thunk';
import logger from 'redux-logger';

import App from './components/app';
import reducers from './reducers';
require('./style.scss');

const createStoreWithMiddleware = applyMiddleware(ReduxThunk)(createStore);

ReactDOM.render(
  <Provider store={createStoreWithMiddleware(reducers)}>
    <App />
  </Provider>,
  document.querySelector('#app')
);
like image 877
doctopus Avatar asked May 13 '17 16:05

doctopus


People also ask

How can you add multiple middleware in Redux?

You can simply pass the middlewares in the comma separated manner like the following code: const store = createStore(reducer, applyMiddleware(thunk, logger)); Note: Please import the applyMiddlware, thunk, and logger at the top.

Which middleware is best in Redux?

Redux thunk is the most popular middleware that allows you to call action creators, which then returns a function instead of an action object.

Can we use Redux without middleware?

The answer is Yes! This blog will try to explain on how to implement async action calls in redux without the use of any middlewares. We will just implement two API calls to not to over complicate things. Create a new file called api.

What is applyMiddleware in react Redux?

middleware) Middleware is the suggested way to extend Redux with custom functionality. Middleware lets you wrap the store's dispatch method for fun and profit. The key feature of middleware is that it is composable.


3 Answers

applyMiddleware takes each piece of middleware as a new argument (not an array). So just pass in each piece of middleware you'd like.

const createStoreWithMiddleware = applyMiddleware(ReduxThunk, logger)(createStore);
like image 139
Andy Noelker Avatar answered Oct 18 '22 23:10

Andy Noelker


answer of andy's is good, but, consider your middlewares growing, below codes will be better:

const middlewares = [ReduxThunk, logger]
applyMiddleware(...middlewares)
like image 31
chen Jacky Avatar answered Oct 18 '22 21:10

chen Jacky


applyMiddleware should pass into createStore as the second parameter. applyMiddleware can have multiple middlewares as arguments.

const store = createStore(reducers, applyMiddleware(ReduxThunk, logger));

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.querySelector('#app')
);
like image 11
Tharaka Wijebandara Avatar answered Oct 18 '22 21:10

Tharaka Wijebandara