combineReducers() not working in React Redux

Viewed 791

This is my Code for Store

import { combineReducers, createStore } from "redux";
 
import counterReducer from "./../Counter/counter.reducer";
const rootReducer = combineReducers({ first: counterReducer });
 
const store = createStore(rootReducer);

export default store;

and the Component :

const Sid = () => {
  const num = useSelector((state) => state.counter);
  const dispatch = useDispatch();
  return (
    <div>
      <h1>Count value is {num}</h1>
      
      <button onClick={() => dispatch(increaseCounter())}>Add 5 </button>
      <button onClick={() => dispatch(decreaseCounter())}>Subtract 50</button>
    </div>
   
  );
}; 

Output:

output

Code Works Fine If I don't use combine reducer and directly use single reducer in the createStore() function

Please help me to solve this issue. Thanks in advance for your help.

2 Answers

When you use combineRreducers, your store object will have the same keys as the object you pass in with the reducer return value as the value.

So in your case the store should look like this

{
  first: {
    counter: 0
  }
} 

the problem is that you try to read the value from state.counter in your selector instead of state.first.counter

Simply change your selector to

const num = useSelector(state => state.first.counter);

A piece of advice. Always write every line of code with a purpose.

According to the official documentation, combineReducers use for below mentioned scenarios.

As your app grows more complex, you'll want to split your reducing function into separate functions, each managing independent parts of the state.

You have only one reducer. Then don't need to combine reducers. Just pass your reducer simply as mentioned below.

import { createStore } from "redux";
import counterReducer from "./../Counter/counter.reducer";

const store = createStore(counterReducer); // Just pass `counterReducer` directly

export default store;

Let me know if you need further support.

Related