Javascript Tips: Scope your case blocks with curly brackets

Written by James McDonald

July 14, 2018

Give your react props default values

If you pass null as a prop then you get warnings about going from a controlled to uncontrolled component


const myValue = this.props.myValue ? this.props.myValue : ''

Renaming variables when destructuring

https://wesbos.com/destructuring-renaming/

// this is a pattern you use alot in react 
const { meetingId, partsObject, partsIds } = this.props
// but sometimes you want to rename the assigned variables
// so you can do that using this pattern
const { meetingId: newName, partsObject, partsIds: newNameHere } = this.props
// then you can use newName or newNameHere

Scope your cases

Just discovered that you should put curly braces after your reducer actions so that you scope your variables inside the case block. You can then reuse the variable names without getting duplicate variable declaration warnings

export const meetingsById = (state = [], action) => {
    switch (action.type) {
        case actionTypes.DELETE_MEETING:
            let newState = state.slice()
            let index = newState.indexOf(action.meetingId.toString())
            newState.splice(index, 1);
            return newState
        case actionTypes.ADD_MEETING:
            let newState // this errors out
            return state.concat(action.id)
        case actionTypes.ANOTHER_ACTION: {
            // putting braces around the case block
            // scopes any variables to within the block
            let newState = state.slice()
            let index = newState.indexOf(action.meetingId.toString())
            newState.splice(index, 1);
            return newState
        }
        case actionTypes.AND_ANOTHER_ACTION: {
            let newState = state.slice() // this works
            return newState.concat(action.id)
        }
        default:
            return state
    }

}

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

You May Also Like…

How to Research a CPU Upgrade

How to Research a CPU Upgrade

Upgrade Time! Doing a lot of VMWare Workstation virtualization to create labs for self-study and training. Finding...