Djaenike
Djaenike

Reputation: 1865

Inserting new element into empty JSON object

I'm trying to insert data into an empty JSON array, but am having trouble. I'm defining the array in the constructor, then making a couple get requests to the back-end when the page loads, and after getting the response I want to add the new array element to the existing. This is the code I am using:

constructor() {
        super();
        this.state = {
            sds: []
        }
    }

    componentDidMount() {
      axios.get('/userData', {
          params: {
              user: this.props.auth.user.name
          }
      }).then(res => {
        for(var i=0; i<res.data[0].chemID.split(',').length; i++){
          if(res.data[0].chemID.split(',')[i] != 0){
              axios.get('/chemData', {
              params: {
                id: res.data[0].chemID.split(',')[i]
              }
             //This is where I want to insert the data
            }).then(res => this.sds += ({
              id: i,
              title: res.data[0].chemName,
              selected: false,
              key: 'sds'
            }))
          }          
        }
      })
  }

Upvotes: 1

Views: 300

Answers (4)

Fernando Perez
Fernando Perez

Reputation: 66

You can try using the next example:

this.state.sds[this.state.sds.length] = {
          id: i,
          title: res.data[0].chemName,
          selected: false,
          key: 'sds'
        }

[Edited]

Like @larz said, you must use the setState method to avoid unexpected result of your code.

var newSds = this.stage.sds;
newSds[newSds.length] = {
      id: i,
      title: res.data[0].chemName,
      selected: false,
      key: 'sds'
    };
this.setState({ sds: newSds});

You can get more information about the lifecycle in react here and the "state updates are merged" here

Upvotes: 0

MauriceNino
MauriceNino

Reputation: 6757

You need to add to your array by using the push() method like this:

constructor() {
    super();
    this.state = {
        sds: []
    }
}

componentDidMount() {
  axios.get('/userData', {
      params: {
          user: this.props.auth.user.name
      }
  }).then(res => {
    for(var i=0; i<res.data[0].chemID.split(',').length; i++){
      if(res.data[0].chemID.split(',')[i] != 0){
          axios.get('/chemData', {
          params: {
            id: res.data[0].chemID.split(',')[i]
          }
         //This is where I want to insert the data
        }).then(res => {
          this.state.sds.push({
            id: i,
            title: res.data[0].chemName,
            selected: false,
            key: 'sds'
          })
        })
      }          
    }
  })
 }

Upvotes: 0

Piyush N
Piyush N

Reputation: 794

You can use array.push().
this.state.sds.push(obj);

If you are not using react setState method than, you need to refer any state variable using this.state.variableName.

Upvotes: 0

larz
larz

Reputation: 5766

+= doesn't work like that. Use a spread operator to copy the previous contents of the array, then add the new object in manually -

}).then((res) => {
  const newThing = {
    id: i,
    title: res.data[0].chemName,
    selected: false,
    key: 'sds'
  };

  this.setState(prevState => ({
    sds: [...prevState.sds, newThing]
  }))
}

You should never try to mutate the state yourself, always use setState. In this case, you can pass a function as the first parameter, which provides the previous state. That way, you can ensure whatever was in this.state.sds is preserved, and your new object is added to that array.

Upvotes: 2

Related Questions