Write a Counter with Redux

Write a Counter with Redux
0.0 0

#1

Tell us what’s happening:

Your code so far


const INCREMENT = 'INCREMENT'; // define a constant for increment action types
const DECREMENT = 'DECREMENT'; // define a constant for decrement action types

const counterReducer = (state = 0, action) => {
  switch(action.type){
  case INCREMENT: 
    return state + 1;
  break;

  case DECREMENT : 
    return state -1;
  break;

  default: 
 return state;

  }
  
}; // define the counter reducer which will increment or decrement the state based on the action it receives

const incAction = () => {
  return {
    type : INCREMENT
  }
}; // define an action creator for incrementing

const decAction = () => {
  
  return {
    type: DECREMENT
  }
  
}; // define an action creator for decrementing

const store = Redux.createStore(counterReducer); // define the Redux store here, passing in your reducers

Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/front-end-libraries/redux/write-a-counter-with-redux


#2

Passes for me, did you have a question?


#3

Hi there,
in place of:
case INCREMENT:
return state + 1;
break;

I wrote:
return state++;
and it won’t work. Would anyone care to explain why?


#4

One of the rules of Redux is “Do not mutate state.” You are not supposed to change it.

return state + 1; does not mutate state. It creates a new number by taking the old state and adding 1 to it.

return state++; is actually changing state. It is going to that memory location and changing the variable adding 1 to it, altering the original.

Never mutate state. Period. Every time we mutate state, a puppy dies. Or more accurately, Redux cannot work properly.