Sometimes, we want to fix the Redux store does not have a valid reducer error in React.
In this article, we’ll look at how to fix the Redux store does not have a valid reducer error in React.
How to fix the Redux store does not have a valid reducer error in React?
To fix the Redux store does not have a valid reducer error in React, we can call combineReducer
with an object that has the state property name as keys and the corresponding reducer as the values.
For instance, we write:
import React from "react";
import { Provider, useDispatch, useSelector } from "react-redux";
import { combineReducers, createStore } from "redux";
const CountReducer = (state = 0, action) => {
switch (action.type) {
case "ADD":
return state + 1;
default:
return state;
}
};
const rootReducer = combineReducers({
count: CountReducer
});
const store = createStore(rootReducer);
const Counter = () => {
const count = useSelector((s) => s.count);
const dispatch = useDispatch();
return (
<div>
<button onClick={() => dispatch({ type: "ADD" })}>+</button>
<span>{count}</span>
</div>
);
};
export default function App() {
return (
<Provider store={store}>
<Counter />
</Provider>
);
}
We have the CountReducer
reducer function that returns the state + 1
if the 'ADD'
action type is dispatched.
Then we call combineReducers
with an object with the count
as the state property name and the CounterReducer
as its reducer.
Next, we call createStore
with rootReducer
to create the store from the root reducer.
Then we create the Counter
component that calls the useSelector
hook to return the the value of the count
state.
And we call the useDispatch
hook to return the dispatch
function that we can use to dispatch actions.
Finally, in App
, we wrap Provider
around Counter
so useSelector
and useDispatch
can be used in Counter
.
And we set the store
prop to the store
so we can dispatch actions and get states from the store.
Conclusion
To fix the Redux store does not have a valid reducer error in React, we can call combineReducer
with an object that has the state property name as keys and the corresponding reducer as the values.