Why u do dis
Why u do dis

Reputation: 458

Redux state is being overwritten by other state change

I am new to redux and I was testing it by creating a theme toggler and a counter.

the problem is everytime i click to increment the counter that works fine but when i try to toggle the dark theme the count resets to 0 and vice versa. I am using combineReducers which holds the themeReducer and counterReducer.

Why is the counter getting reset on state change? what am i doing wrong?

here is some code:

Actions:

 export function increment() {
  return {
    type: 'INCREMENT',
  };
}

export function decrement() {
  return {
    type: 'DECREMENT',
  };
}

//different file
    export function darkTheme() {
      return {
        type: 'DARK',
      };
    }

Reducers:

export default function counterReducer(state = 0, action) {
  switch (action.type) {
    case 'INCREMENT':
      return state + 1;
    case 'DECREMENT':
      return state - 1;
    default:
      return 0;
  }
}

//different file
export default function themeReducer(state = false, action) {
  switch (action.type) {
    case 'DARK':
      return !state;
    default:
      return false;
  }
}

im calling it like this :

 const dispatch = useDispatch();
   <button onClick={() => dispatch(increment())}> +</button>

Upvotes: 0

Views: 21

Answers (1)

phry
phry

Reputation: 44086

You have to always return state in the default case, in both reducers: every reducer will always be called with every action, so they have to do no modification to the existing state in the default case.

All that said, I want to make you aware that you are learning "vanilla redux" here, which is not the recommended style of redux for production use any more. So while that is great to get an understanding of the underlying concepts, you should not really write code like this in the end. Please follow the official redux tutorials to get an understanding on how to write modern redux. (The fundamentals tutorial will get you started with the style you are using right now and then move into more modern territory, the essentials tutorial will start directly with modern redux - both ways are valid for learning redux)

Upvotes: 2

Related Questions