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 *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.

You May Also Like…

Squarespace Image Export

To gain continued access to your Squarespace website images after cancelling your subscription you have several...

MySQL 8.x GRANT ALL STATEMENT

-- CREATE CREATE USER 'tgnrestoreuser'@'localhost' IDENTIFIED BY 'AppleSauceLoveBird2024'; GRANT ALL PRIVILEGES ON...

Exetel Opt-Out of CGNAT

If your port forwards and inbound and/or outbound site-to-site VPN's have failed when switching to Exetel due to their...