I tried simple react,redux,ajax working example and followed Reddit API tutorial, but I cannot create store and get error:
Uncaught Error: Expected the reducer to be a function.
index.jsx
...
import { createStore, applyMiddleware } from 'redux' var thunkMiddleware = require('redux-thunk'); var createLogger = require('redux-logger'); var rootReducer = require('./reducers.js'); const loggerMiddleware = createLogger(); function configureStore(initialState) { return createStore( rootReducer, initialState, applyMiddleware( thunkMiddleware, loggerMiddleware ) ) } const store = configureStore();
...
rootReducer.js
import { combineReducers } from 'redux'; function products(state = { isFetching: false, didInvalidate: false, items: [] }, action) { switch (action.type) { case 'REQUEST_PRODUCTS': return Object.assign({}, state, { isFetching: true, didInvalidate: false }) case 'RECEIVE_PRODUCTS': return Object.assign({}, state, { isFetching: false, didInvalidate: false, items: action.posts, lastUpdated: action.receivedAt }) default: return state } } function specialPosts(state = { }, action) { switch (action.type) { case RECEIVE_SPECPOSTS: case REQUEST_SPECPOSTS: return Object.assign({}, state, { req: true }) default: return state } } const rootReducer = combineReducers({ products, specialPosts }); export default rootReducer;
Type of rootReducer is object, but why? Should I change createStore
function to rootReducer.default
?
return createStore( rootReducer.default, initialState, applyMiddleware( thunkMiddleware, loggerMiddleware ) )
package.json
"redux-logger": "^2.6.1", "react-redux": "^4.4.1", "react-redux-provide": "^5.2.3", "redux": "^3.3.1", "redux-thunk": "^2.0.1",
const rootReducer = combineReducers({ products, specialPosts }); const store = createStore( rootReducer, applyMiddleware( thunkMiddleware ));
The initial state is then created automatically from the initial states returned by the individual reducer functions. These individual states can be accessed as state.products
and state.specialPosts
The problem was due to rootReducer being imported by "require" (ES5):
var rootReducer = require('./reducers.js');
If you import it via the ES6 method, it will correctly save the rootReducer.js' default automatically into rootReducer as you expected:
import rootReducer from './reducers';
I see you are mixing ES5 (require) and ES6 (import) in that file...I was mixing in my project as well, which is why I ran into this problem. More information can be found here: https://medium.com/@kentcdodds/misunderstanding-es6-modules-upgrading-babel-tears-and-a-solution-ad2d5ab93ce0#.2x2p2dx3m
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