modernator modernator - 1 month ago 8
React JSX Question

applying middleware on store is not called reducer correctly in Redux

i'm making website with React + Redux. before i added middleware, application works fine, but after added, reducer not dispatching correctly.

this is my code:

import { createStore, applyMiddleware } from 'redux';

...

let createStoreWithMiddleware = applyMiddleware(logger)(createStore);

let store = createStoreWithMiddleware(appReducer);

store.dispatch(updateText('text changed.'));


and this is my action creator just used above:

const UPDATE_TEXT = 'UPDATE_TEXT';

function updateText(text = '') {
return {
type: UPDATE_TEXT,
text
};
}


and this is appReducer:

const defaultState = { text: 'default' };
function appReducer(state = defaultState, action) {
switch(action.type) {
case UPDATE_TEXT:
return Object.assign({}, state, {
text: action.text
});
default:
return state;
}
}


if i just remove applyMiddleware and create store directly with use createStore like this:

let store = createStore(appReducer);


it works fine! but i really want to use middlewares. what should i do? anyone gimme a hand will be very appreciate!

Answer Source

In older versions of redux-logger (which you may be using), the initial import was a function that needed to first be called like this:

import createLogger from 'redux-logger'
const logger = createLogger()

Then you could use logger as middleware:

...
const createStoreWithMiddleware = applyMiddleware(logger)(createStore)
...

However, in the current version, you can simply import logger from 'redux-logger' and use it that way. If you want to create a logger with custom options, you can import { createLogger } from 'redux-logger'.