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')
);
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.
Redux thunk is the most popular middleware that allows you to call action creators, which then returns a function instead of an action object.
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.
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.
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);
answer of andy's is good, but, consider your middlewares growing, below codes will be better:
const middlewares = [ReduxThunk, logger]
applyMiddleware(...middlewares)
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')
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With