Can't get "incAction" to work : Write a Counter with Redux

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 defaultState = 0;
const counterReducer=(state=defaultState, action)=>{ 
    switch(action.type){
        case INCREMENT:
        state++;

        case DECREMENT:
        state--;

        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}};
const decAction = () => { return {type: DECREMENT}}; 
const store = Redux.createStore(counterReducer);

console.log(store.getState());

Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64; rv:64.0) Gecko/20100101 Firefox/64.0.

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

Hi @nzanoa,

Everything looks good except you’re missing return statements in your other cases in switch statement and you’d have to use pre-increment/decerement operator rather than post-increment/decrement operator.

switch(action.type){
        case INCREMENT:
        return ++state;

        case DECREMENT:
        return --state;

This should do it.

1 Like

Thanks a lot @ezioda004!
But I would like to understand why the post increment didn’t work in this case?

I don’t know if you’re still interested in knowing the answer to this question, but I think it’s because the return keyword and state++ are in the same line.

function postIncOneLine() {
  var state = 0;
  return state++;
}

postIncOneLine(); // 0 <-- It's zero :(
function postIncTwoLines() {
  var state = 0;
  state++;
  return state; 
}

postIncTwoLines(); // 1 <-- It's one :)

And I think the reason for this discrepancy has to do with the fact that the postfix increment operator returns a value before incrementing [Source: MDN].

So when we do return state++;, state++ returns 0. So we return 0.

We see something similar in the MDN increment example:

var x = 3;
y = x++; // y = 3, x = 4

Notice that y is equal to 3, not 4, because x++ returns 3.

When we do

function postIncTwoLines() {
  var state = 0;
  state++;
  return state; // 1
}

It’s like doing this:

var state = 0;
state++; // 0
console.log(state); // 1

We get the expected result, 1, because we’re returning state after the value has been returned, and after the value has been incremented.

TL;DR The postfix increment operator will first return the value, and then it will increment the value.

From reading Stack Overflow, I think it’s something like state = value, and value is 0 at first, but then value gets updated to 1.
Someone who has a better understanding the specs and how the engine works will be able to give a better explanation.