Search code examples
javascriptreactjsobjectreturnsetstate

Difference between returning object literal vs raw values directly in this.setState? (React.JS)


My goal is to change a state object through a this.setState method, but there's a thing that makes me confusing.

First, I created an object literal called newCount, gave a new key: value pair data and returned the newCount, but the browser doesn't increase the count value what I expected.

this is the code:

this.setState(prevState => {
    var newCount = {
        count: prevState.count + 1
    } // It won't increase. Just keeps showing 1.
    return {
        newCount
    }
})

But when I try to return the values directly like this, it works:

this.setState(prevState => {
    return {
        count: prevState.count + 1
    } // It goes working. 
})

What's the difference between those 2 code blocks?


Solution

  • The first code sample creates a new field inside state called newCount:

    return {
       newCount, // es6 shorthand - equals to `newCount: newCount`
    }
    

    The second example works correctly since you are updating the proper count field.

    If you would like to make it work in both ways, just add a correct field name:

    return {
       count: prevState.count + 1, // or `count: newCount.count`
    }
    

    More details about objects initializing: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer