1

I have an array inside an state which is an associative array. I want to insert values into this array when an event occurs.

State Declaration I used.

state = {
    array: [{
        aaa: '',
        bbb: ''
    }]
};

Function which is supposed to insert values to the array inside state.

reader.onload = (e) => {

    var newArray = {
        aaa: new_aaa,
        bbb: new_bbb
    }
    this.setState({
        array: this.state.array.concat(newArray)
    });

}

Somehow , it isn't working ^_^

1
  • Have you tried with given answers? If yes then please do upvote and accept the answer. Thanks Commented Oct 27, 2018 at 5:51

2 Answers 2

1

You could use Destructuring_assignment when you are setting your state.

state = {
  array: [{
    aaa: '',
    bbb: ''
  }]
};

reader.onload = (e) => {
  var newArray = {
    aaa: new_aaa,
    bbb: new_bbb
  }
  this.setState({
    array: [...this.state.array,newArray]
  });
}
Sign up to request clarification or add additional context in comments.

Comments

1

Try with below code. The best approach to push values or object to an array in React is using previous state like below

  reader.onload = (e) => {
       const obj = {
           aaa: new_aaa,
           bbb: new_bbb
        }
       this.setState( prevState => ({
              array: [...prevState.array, obj]
        }));
   }

Or

   reader.onload = (e) => {
       const obj = {
           aaa: new_aaa,
           bbb: new_bbb
        }
       const array = [...this.state.array];
       array.push(obj);
       this.setState({
              array
        });
   }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.