samedi 4 juillet 2020

Where to put conditional statement when setting state in React.js?

I am making a Pomodoro Clock project from freeCodeCamp using React.js. I want to change the state conditionally based on the current state. Do I need to use this.state or the state argument from the updater function in setState?

Here is my code:

Using state argument:

this.setState(state => {
    let newState = {}
    if (state.timer === 0){
        this.beep.current.play()
        if (state.type === 'Session') {
            newState.timer = state.break * 60
            newState.type = 'Break'
        } else {
            newState.timer = state.session * 60
            newState.type = 'Session'
        }
    } else {
        newState.timer = state.timer - 1
    }
    return newState
})

Using this.state:

if (this.state.timer === 0) {
    this.beep.current.play()
    if (this.state.type === 'Session') {
        this.setState(state => ({
            timer: state.break * 60,
            type: 'Break'
        }))
    } else {
        this.setState(state => ({
            timer: state.session * 60,
            type: 'Session'
        }))
    }
} else {
    this.setState(state => ({
        timer: state.timer - 1
    }))
}

If you need more context, you can see both codes on CodePen using this.state and without this.state. You can run the test on the upper left corner. As you can see in the CodePen that both codes pass the test. Which of those should I use and why?

Aucun commentaire:

Enregistrer un commentaire