Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

combineReducers() not working in React Redux

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.

like image 945
Siddhesh B. Kukade Avatar asked Oct 31 '25 17:10

Siddhesh B. Kukade


1 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);
like image 59
Asaf Aviv Avatar answered Nov 02 '25 06:11

Asaf Aviv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!