Write a Counter with Redux - Why/how does this work?

Tell us what’s happening:

I’ve technically solved this challenge but don’t understand why/how the solution works.

What are lines 1 and 2 even doing? The variables are never used.

Also, how am I supposed to access the value of state since it is never actually defined?

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': 
            state++; 
            break; 
        case 'DECREMENT': 
            state--;
            break; 
    }
    return state; 
}

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

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

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36.

Link to the challenge:

Hello!

I think line 1 and 2 is meant for defining and storing the action names in variables: INCREMENT and DECREMENT. But I think you’re not utilising that. You should make use of these variables by referring to them rather than explicitly writing the strings 'INCREMENT' and 'DECREMENT'. The benefit of re-using these variables is that it’s easier to refactor the code later on, because you only have to change the value of the INCREMENT variable on one place (where the variable is declared).

Here’s an example with the difference:

const INCREMENT = 'INCREMENT';
const DECREMENT = 'DECREMENT';

const counterReducer = (state = 0, action) => {
    switch (action.type) {
        case INCREMENT: // Re-use INCREMENT variable and not the 'INCREMENT' string
            state++; 
            break; 
        case DECREMENT:  // Re-use DECREMENT variable and not the 'DECREMENT' string
            state--;
            break; 
    }
    return state; 
}

const incAction = () => {
    return {
        type: INCREMENT // Re-use INCREMENT variable and not the 'INCREMENT' string
    }
}; 

const decAction = () => {
    return {
        type: DECREMENT // Re-use DECREMENT variable and not the 'DECREMENT' string
    }
}; 

const store = Redux.createStore(counterReducer); 

I hope my explanation makes sense :slightly_smiling_face:?

1 Like

Actually the main benefit of using constants for action names instead of string literals is that typos become easier to catch. If you accidentally spell a string literal ‘DECERMENT’, it will silently fall through and not change any state, whereas if you typo the constant, it will fail with an error.

2 Likes