Redux | Error: Expected the reducer to be a function - javascript

I'm trying to use Redux, Redux-Thunk in my app. I did it before and it worked but here it keeps showing Error: Expected the reducer to be a function
scr/App.js;
import React, { Component } from 'react';
import { Router } from 'react-router-dom';
import { createBrowserHistory } from 'history';
import { Chart } from 'react-chartjs-2';
import { ThemeProvider } from '#material-ui/styles';
import { chartjs } from './helpers';
import theme from './theme';
import 'react-perfect-scrollbar/dist/css/styles.css';
import './assets/scss/index.scss';
import Routes from './Routes';
import { Provider } from 'react-redux';
// redux
import { createStore, applyMiddleware, compose, combineReducers } from 'redux';
import thunk from 'redux-thunk';
import { composeWithDevTools } from 'redux-devtools-extension/developmentOnly';
import * as actionTypes from './store/actions/actionTypes';
import rootReducer from './store/reducers/rootReducer';
const browserHistory = createBrowserHistory();
Chart.helpers.extend(Chart.elements.Rectangle.prototype, {
draw: chartjs.draw
});
const store = createStore(
rootReducer,
compose(applyMiddleware(thunk), composeWithDevTools)
);
export default class App extends Component {
render() {
return (
<Provider store={store}>
<ThemeProvider theme={theme}>
<Router history={browserHistory}>
<Routes />
</Router>
</ThemeProvider>
</Provider>
);
}
}
when I tried to log rootReducer it logged an empty line for the initial load then the app breaks then it logs the rootReducer
src/store/rootReducer.js
import { combineReducers } from 'redux';
import searchReducer from './searchReducer';
const rootReducer = combineReducers({
searchReducer: searchReducer
});
export default rootReducer;
src/store/reducers/searchReducer.js
import * as actionTypes from '../actions/actionTypes';
const initialState = {
loading: false,
result: [],
error: ''
};
const searchReducer = (state = initialState, action) => {
switch (action.type) {
case actionTypes.SEARCH_TRIGGER:
return {
...state,
loading: true,
result: [],
error: ''
};
case actionTypes.SEARCH_ERROR:
return {
...state,
loading: false,
result: [],
error: action.error
};
case actionTypes.SEARCH_SUCCESS:
return {
...state,
loading: false,
error: '',
result: action.result
};
default:
return state;
}
};
export default searchReducer;
src/store/actions/actionTypes.js
// create campaign actions
export const UPDATE_STEPPER_STATE = 'UPDATE_STEPPER_STATE';
export const SEARCH_TRIGGER = 'SEARCH_TRIGGER';
export const SEARCH_SUCCESS = 'SEARCH_SUCCESS';
export const SEARCH_ERROR = 'SEARCH_ERROR';
src/store/actions/stepperActions.js
import * as actionTypes from './actionTypes';
export const updateStepperState = data => {
return {
action: actionTypes.UPDATE_STEPPER_STATE,
data
};
};
exported in index.js inside the same directory
export { updateStepperState } from './stepperActions';
packages
"react-redux": "^7.1.3",
"redux": "^4.0.4",
"redux-devtools-extension": "^2.13.8",
"redux-thunk": "^2.3.0",
"thunk": "0.0.1",

It looks like your path to searchReducer is incorrect.
Change this:
import searchReducer from './searchReducer';
to this:
import searchReducer from './reducers/searchReducer';
in your rootReducer.js file.
It's giving you the error Expected the reducer to be a function because searchReducer is returning undefined.

hey try creating store like this
const store = createStore(
rootReducer,
composeWithDevTools(applyMiddleware(thunk))
);
i think you can not use multiple store enhancers together,you either choose compose or composeWIthDevTools,and create store based on environment like for development use composeWithDevTools and for production use compose

Related

Redux store isn't updating

I am trying to update the redux store with a list of groupsNames.
The axios call inside the action works and there is a response.
When I dispatch the payload the redux store doesnt get updated with response data.
FileName: actions/index.js
CODE:
export const getGroups = () => async dispatch => {
axios.get(url + "groups")
.then(response => {
console.log(response.data);
dispatch({
type: GET_GROUPS,
payload: response.data
})
},
function(error) {
console.log(error)
}
);
};
Filename: reducers/groupsReducer.js
CODE:
import _ from 'lodash';
import {
GET_GROUPS,
} from '../actions/types';
export default (state = {}, action) => {
console.log(action.payload);
console.log("inside groupsREducer");
switch (action.payload) {
case GET_GROUPS:
console.log(action.payload);
return {...state, ..._.mapKeys(action.payload, 'id')};
default:
return state;
}
}
//mapKeys is a function from lowdadsh that takes an array and returns an object.
FileName: reducers/index.js
CODE:
import { combineReducers } from 'redux';
import authReducer from './authReducer';
import { reducer as formReducer } from 'redux-form';
import postsReducer from './postsReducer';
import groupsReducer from './groupsReducer';
export default combineReducers ({
auth: authReducer,
form: formReducer,
posts: postsReducer,
groups: groupsReducer,
});
FileName: GroupList.js
CODE:
import React from "react";
import { connect } from "react-redux";
import { getGroups } from '../../actions';
class GroupList extends React.Component {
componentDidMount() {
this.props.getGroups();
}
render() {
return <div>
<h1>GroupList</h1>
</div>;
}
}
export default connect(null, { getGroups })(GroupList);
FileName: App.js
CODE:
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware, compose} from 'redux';
import reduxThunk from 'redux-thunk';
import reducers from './reducers';
import Landing from './components/Landing';
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(
reducers,
composeEnhancers(applyMiddleware(reduxThunk))
);
ReactDOM.render(
<Provider store={store}>
<Landing />
</Provider>,
document.querySelector('#root')
);```
Ive connected to ReduxDevToolsExtension in chrome and when i check the state in there, it shows empty.
Your are using the wrong argument for your switch-case.
Replace switch (action.payload) with switch (action.type)

React.js Redux actions and reducers do not get initated

I am having an issue with my React-Redux app. I have created Redux action & reducer and connected them to my React component. However, it seems like it never gets to my Redux action & reducer.
I put "debugger" in my action and reducer but those debuggers never get initiated.
Could you please help me fix this issue?
Am I missing something here?
Here the current codes in the following files:
Here is the code for my app.js:
import React, { Component } from 'react';
import { render } from 'react-dom';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import ReduxPromise from 'redux-promise';
import rootReducer from './reducers';
import App from './components/index';
const createStoreWithMiddleware = applyMiddleware(thunk, ReduxPromise)(createStore);
render(
<Provider store={createStoreWithMiddleware(rootReducer)}>
<App />
</Provider>,
document.getElementById('app')
);
Here is my code for index.js:
As you can see below, I put a debugger in the "componentDidMount()", and when In run it, it gets to that point.
import React, { Component } from 'react';
import { render } from 'react-dom';
import { connect } from 'react-redux';
import * as AllNewsApiActions from '../actions/newsApiActions';
import '../../css/style.css';
class App extends Component {
componentDidMount() {
this.props.getNewsApi();
debugger;
}
render() {
return (
<div>
<p>Hello from react</p>
<p>Sample Testing</p>
</div>
);
}
}
const mapStateToProps = (state) => ({
newNews: state.newNews
});
export default connect(mapStateToProps, {
...AllNewsApiActions
})(App);
Here is my action:
import * as types from './newsTypes';
const API_KEY = "6c78608600354f199f3f13ddb0d1e71a";
export const getNewsApi = () => {
debugger;
return (dispatch, getState) => {
dispatch({
type: 'API_REQUEST',
options: {
method: 'GET',
endpoint: `https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=${API_KEY}`,
actionTypes: {
success: types.GET_NEWS_API_SUCCESS,
error: types.GET_NEWS_API_ERROR
}
}
});
}
}
Here is my reducer:
import * as types from '../actions/newsTypes';
const initialState = {
newNews: []
};
const getNewsAPIReducer = (state = initialState, action) => {
switch(action.type) {
case types.GET_NEWS_API_SUCCESS:
debugger;
return { ...state, newNews: action.data };
case types.GET_NEWS_API_ERROR:
debugger;
return { ...state, error: action.data };
default: {
return state;
};
};
};
export default getNewsAPIReducer;
Here is the index.js file in the reducer folder:
import { combineReducers } from 'redux';
import NewsApiReducer from './newsApiReducer.js';
const rootReducer = combineReducers({
newNews: NewsApiReducer
});
export default rootReducer;

redux-persist blacklist not working

I want to blacklist some of my reducers because my state tree is getting bigger and im getting this error:
Could not write debug session to localStorage: DOMException: Failed to execute 'setItem' on 'Storage': Setting the value of 'redux-persist' exceeded the quota.(…)"
The solution I found is to blacklist some reducers that doesn't need to be persisted. So I have this code in my App.js
import React, { Component } from 'react';
import { Provider } from 'react-redux';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import { persistStore } from 'redux-persist'
import { Initializer } from './components';
import store from './store';
class App extends Component {
constructor() {
super()
this.state = { rehydrated: false }
}
componentWillMount(){
persistStore(store, { blacklist: ['project', 'comment', 'project', 'jobOrder']}, () => {
this.setState({ rehydrated: true })
})
}
render() {
if(!this.state.rehydrated)
return <Initializer />;
return (
<Provider store={store}>
<Router>
<div>
<Switch>
... some Routes
</Switch>
</div>
</Router>
</Provider>
);
}
}
export default App;
and I have this rootReducer:
import { reducer as formReducer } from 'redux-form'
import { combineReducers } from 'redux';
import userAuthReducer from './userAuthReducer';
import jobOrderReducer from './jobOrderReducer';
import clientReducer from './clientReducer';
import userReducer from './userReducer';
import persistReducer from './persistReducer';
import commentReducer from './commentReducer';
import projectReducer from './projectReducer';
import teamReducer from './teamReducer';
export default combineReducers({
userAuth: userAuthReducer,
jobOrder: jobOrderReducer,
job_order: jobOrderReducer,
client: clientReducer,
user: userReducer,
form: formReducer,
persist: persistReducer,
comment: commentReducer,
project: projectReducer,
team: teamReducer
});
My persistReducer.js
import { PERSIST } from '../actions/types';
export default (state = [], action) => {
switch(action.type) {
case PERSIST:
return { ...state, ...action.payload }
default:
return state;
}
};
And my store.js
import { compose, createStore, applyMiddleware } from 'redux';
import { autoRehydrate } from 'redux-persist';
import thunk from 'redux-thunk';
//import logger from 'redux-logger';
import rootReducer from './reducers';
const store = createStore(
rootReducer,
{},
compose(
applyMiddleware(thunk, /*logger*/),
autoRehydrate())
);
//persistStore(store);
export default store;
But running the App, I still get the blacklisted persisted state as you can see here:
I tried changing the blacklist keys to:
persistStore(store, { blacklist: ['reduxPersist:project', 'reduxPersist:comment', 'reduxPersist:project', 'reduxPersist:jobOrder']}, () => {
this.setState({ rehydrated: true })
})
But the keys are still persisting... How to properly do this?
I read this article here and the author made a good point, the blacklist isn't looking for the name of the attributes in your redux store, rather in your state. I had the same confusion.
Double check in dev tools what is actually being saved in your local storage. make sure you are blacklisting the correct names.
You need to define blacklist array in both config objects (parent and child).
const rootPersistConfig = {
key: 'root',
storage: AsyncStorage,
blacklist: ['appReducer'], // 2: Need to add child reducer key here too.
};
const appPersistConfig = {
key: 'appReducer',
storage: AsyncStorage,
// 1: Below are the keys to blacklist
blacklist: ['snackbar', 'dayThought', 'updatingBohoId', 'snackbar_notif'],
};

React-Redux Uncaught Error: Expected the reducer to be a function

The github repo for this project: https://github.com/leongaban/react_starwars
Expected
My basic app runs without errors, and in the chrome devtools Redux tab, I see a list of star wars characters
Results
The main index.js
import React from 'react'
import ReactDOM from 'react-dom'
import App from './components/App'
import { createStore, applyMiddleware, compose } from 'redux'
import { Provider } from 'react-redux'
import thunk from 'redux-thunk'
import reducer from './reducer'
import { getCharacters } from './reducer/characters/actions'
const store = createStore(reducer, compose(
applyMiddleware(thunk),
window.devToolsExtension ? window.devToolsExtension : f => f
));
store.dispatch(getCharacters())
const container = document.getElementById('app-container');
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>
, container);
My src > reducer > characters > actions.js
import { API_URL } from '../../constants'
export const SET_CHARACTERS = 'SET_CHARACTERS'
export function getCharacters() {
return dispatch => {
fetch(`${API_URL}/people`)
.then(res => res.json())
.then(res => res.results)
.then(characters =>
dispatch(setCharacters(characters))
)
}
}
export function setCharacters(characters) {
return {
type: SET_CHARACTERS,
characters
}
}
reducer > characters > index.js
import { SET_CHARACTERS } from './actions'
const initialState = [];
export default (state = initialState, action) => {
switch(action.type) {
case SET_CHARACTERS:
return action.characters;
default:
return state;
}
}
reducer > index.js
import { combineReducers } from 'redux'
import characters from './characters'
export default combineReducers({
characters
})
try
const createFinalStore = compose(
applyMiddleware(thunk)
)(createStore)
const store = createFinalStore(reducer, initialState /* or {} */);
i don't think the createStore redux api wants you to pass the middleware as the second argument. that should be the initial/preloaded state
http://redux.js.org/docs/api/createStore.html

React + Redux-router = Uncaught Error: Expected the reducer to be a function

My code is working fine, but I have an annoying problem whenever I make a coding mistake and get a runtime error. For instance, in one of my JSX pages I did Date() instead of new Date() and instead of reporting the actual error, I got...
Uncaught Error: Expected the reducer to be a function.
Any error I make almost always shows up as this. It's being reported from createStore.js, which is in my configureStore.jsx code below.
Is there a way that I can get better error reporting that helps me identify the real problem? Any help or ideas are greatly appreciated!!!
Here's my setup for reference....
main.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { ReduxRouter } from 'redux-router';
import configureStore from './store/configureStore'
import routes from './routes';
const rootEl = document.getElementById('app-container');
const store = configureStore();
ReactDOM.render(
<div>
<Provider store={store}>
<ReduxRouter routes={routes} />
</Provider>
</div>
, rootEl
);
configureStore.jsx
import { createHashHistory } from 'history';
import { applyMiddleware, createStore, compose } from 'redux';
import { reduxReactRouter } from 'redux-router';
import thunk from 'redux-thunk';
import promiseMiddleware from 'redux-promise-middleware';
import rootReducer from '../reducers/rootReducer';
import routes from '../routes';
export default function configureStore(initialState = {}) {
const history = createHashHistory();
const middlewares = [
thunk,
promiseMiddleware({
promiseTypeSuffixes: ['PENDING','SUCCESS','ERROR']
})
];
const toolChain = [
applyMiddleware(...middlewares),
reduxReactRouter({
routes,
history
})
];
const store = compose(...toolChain)(createStore)(rootReducer, initialState);
if (module.hot) {
module.hot.accept('../reducers', () => {
const nextRootReducer = require('../reducers/rootReducer');
store.replaceReducer(nextRootReducer);
});
}
return store;
}
rootReducer.jsx
import { combineReducers } from 'redux';
import { routerStateReducer } from 'redux-router';
import siteReducer from './siteReducer';
const rootReducer = combineReducers({
router: routerStateReducer,
sites: siteReducer
});
export default rootReducer;
siteReducer.jsx
import {GET_SITES} from '../actions/siteActions';
const defaultState = {
isPending: null,
isSuccess: null,
isError: null,
error: null,
data: null
};
export default function siteReducer(state = defaultState, action) {
switch (action.type) {
case `${GET_SITES}_PENDING`:
return {
...defaultState,
isPending: true
};
case `${GET_SITES}_SUCCESS`:
return {
...defaultState,
isSuccess: true,
error: false,
data: action.payload
};
case `${GET_SITES}_ERROR`:
return {
...defaultState,
isError: true,
error: action.payload
};
default:
return state;
}
}
Change the following line:
const nextRootReducer = require('../reducers/rootReducer');
To:
const nextRootReducer = require('../reducers/rootReducer').default;
Use export const variable_name instead of const variable_name whenever you want to export that variable.
For ex: rootReducer.jsx should be re-written as
import { combineReducers } from 'redux';
import { routerStateReducer } from 'redux-router';
import siteReducer from './siteReducer';
export const rootReducer = combineReducers({
router: routerStateReducer,
sites: siteReducer
});
export default rootReducer;
Note the extra export specifier with const rootReducer
My issue was importing Store from the root reducer path rather than the actual bundled store root (with devtools on the window and root reducer, middleware being composed, etc).
import Store from '../../../src/state/Store/reducer';
changed to
import Store from '../../../src/state/Store';

Categories

Resources