ReactJS - push json into state array

Ad

I'm simply trying to append a json created dynamically into an array that lives inside the state. The only way that I've found till now is to use concat, because push doesn't work.

    constructor() {
        super()
        this.state = {
            list: []
        }
        this.add = this.add.bind(this)
    }

    add(e) {
        e.preventDefault()
        var task = document.getElementById('task').value
        var json = JSON.parse(JSON.stringify({key: task, item: task}))
        this.setState({list: this.state.list.concat(json)}) // WORKS
        // this.setState({list: this.state.list.push(json)}) // DOESN'T WORK

        console.log(this.state.list)
        document.getElementById('task').value = ''

    }

That works, but I don't understand why I have an empty array in console after the first item it's created. I've read how concat works, but obviously I missed something. Why I can't push an object inside my this.list array?

Ad

Answer

Ad

The concat otherwise create a new array and return it.

The push returns the new length of the array, which means a number, which means NOT what you want to set to state.list. That's why it didn't work.

why I have an empty array in console

From the docs: setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value. That's why you are getting the empty array in the console.

And one more thing, don't mutate your state directly. If you call state.list.push(...), your changes will not be maintained by React and will be discarded if you call setState later. So it's a good thing to use concat.

Ad
source: stackoverflow.com
Ad