[Solved] How to push new object in an array?


The problem is you assign an empty array every time you call the function

 radioButtonVal = (e) => {
    this.radioid = e.target.name;
    this.radiovalue = e.target.value;
    this.radioButtonValTitles = []; //right here you initiate an empty array
    this.radioButtonValFind = this.radioButtonValTitles.find(x => x.id === this.radioid);
    if(this.radioButtonValFind){
        this.radioButtonValFind.id = this.radioid;
        this.radioButtonValFind.value = this.radiovalue;
    } else {
        this.radioButtonValTitles.push({id: this.radioid, value: this.radiovalue})
    }
}

What you should do is keep radioButtonValTitles in your state, and refer to them later, like this:

constructor(props) {
    super(props);

    this.state = {
        radioButtonValTitles: [],
    };  
}

and then modify your function like this:

 radioButtonVal = (e) => {
    const { radioButtonValTitles } = this.state;

    this.radioid = e.target.name;
    this.radiovalue = e.target.value;
    this.radioButtonValFind = radioButtonValTitles.find(x => x.id === this.radioid);
    if(this.radioButtonValFind){
        this.radioButtonValFind.id = this.radioid;
        this.radioButtonValFind.value = this.radiovalue;
    } else {
        this.setState({
            radioButtonValTitles: radioButtonValTitles.push({id: this.radioid, value: this.radiovalue})
        )}
    }
}

1

solved How to push new object in an array?