to this.state = { answer: []} which works fine. At the same time when the user update answer it add as another object. Is there any option to update the object in setState when the questionID is the same ?
onChange(event) {
const field = event.target.name;
let question = event.target.dataset.questionId;
let result = event.target.value;
let answer = {
'questionID': question,
'answerValues': result
};
this.setState({
answer: [
...this.state.answer,
answer,
]
});
console.log(this.state.answer);
}
Currently same question adding like this
[
{
"questionID": 1,
"answerValues": 2
},
{
"questionID": 2,
"answerValues": 5
}
{
"questionID": 1,
"answerValues": 1
}
]
any solution to update the object if already exist same questionID is this.state.answer ?
you can try this.setState( { answer:[ ...this.state.answer.filter(a=>a.questionID!==question), answer, ] });
Обсуждают сегодня