JavaScript ReactJS - push json into state array push json reactjs

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?

Answer:1

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.

Answer:2

this.state is immutable and has to be changed only via the setState() function.

From the docs:

NEVER mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable. 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.

So, the best way to do this is to replace the array in this.state by a new array, and not try to push/modify it.

var newState = Object.assign({}, this.state); // Clone the state obj in newState
newState[arrayKey].push(newItem);             // modify newState
this.setState(newState);                      // setState()
Answer:3

I am using an AJAX script to submit a basic contact form at the bottom of my HTML that uses Google reCAPTCHA. The html code is: <div class="col-md-6"> <form role="form" id="form" ...

I am using an AJAX script to submit a basic contact form at the bottom of my HTML that uses Google reCAPTCHA. The html code is: <div class="col-md-6"> <form role="form" id="form" ...

Here is my code: var arr = [[[[[]]]]]; var c = 20; for (i=0;i<5;i++) arr[i][0][0][0] = c; alert(arr[2][0][0][0]); It doesn't work, but how can I do this?

Here is my code: var arr = [[[[[]]]]]; var c = 20; for (i=0;i<5;i++) arr[i][0][0][0] = c; alert(arr[2][0][0][0]); It doesn't work, but how can I do this?

  1. initialize array javascript with values
  2. initialize array javascript with size
  3. initialize array javascript with 0
  4. initialize array javascript empty
  5. initialize array javascript es6
  6. initialize array javascript object
  7. initialize 2d array javascript
  8. initialize multidimensional array javascript
  9. initialize new array javascript
  10. initialize array length javascript
  11. initialize json array javascript
  12. initialize string array javascript
  13. initialize associative array javascript
  14. initialize blank array javascript
  15. initialize boolean array javascript
  16. initialize null array javascript
  17. initialize double array javascript
  18. initialize dynamic array javascript
  19. initialize 3d array javascript
  20. re initialize array javascript

What is the best way to perform a NOT operation? For example, here's the javascript Template.mytemplate.helper({ myhelper : function(){ return true; } }); Now how would I get !myhelper in a ...

What is the best way to perform a NOT operation? For example, here's the javascript Template.mytemplate.helper({ myhelper : function(){ return true; } }); Now how would I get !myhelper in a ...

  1. helper t cells
  2. helper helper
  3. helper utah
  4. helper synonym
  5. helper springs
  6. helper t cells function
  7. helper t cells definition
  8. helpers inc
  9. helper jobs
  10. helper monkey
  11. helper definition
  12. helper act
  13. helper clinic
  14. helper tools for instagram
  15. helper in spanish
  16. helper utah weather
  17. helper stool
  18. helper tower
  19. helper jobs near me
  20. helper crossword clue

I am currently trying to get my head around database's and web programming. I currently have 3 files index.html, script.js (empty at the minute) and test_db.sqlite. I am trying to pull info from the ...

I am currently trying to get my head around database's and web programming. I currently have 3 files index.html, script.js (empty at the minute) and test_db.sqlite. I am trying to pull info from the ...

  1. sqlite reading writing