i need your help to set the new value in multiple object. I had object like this:
constructor(props){
this.state = {
objData : [{
score:{q1:null,q2:null,q3:null},
data:{id:123, name:"Steven CHS"}
},
{
score:{q1:null,q2:null,q3:null},
data:{id:124, name:"Christian"}
},
]
}
}
and i would like to change the value by key q1,q2, anda q3. When i tried to use destructor like this, it’s not working.
const handleChangeScore = (e,type,id) =>{
const cScore = e.target.value;
this.setState((state) => {
return {
objData: state.objData.map((item) => {
if(item.data.id !== e.target.name) return item;
else return {...item.score.q1, cScore};
})
};
});
}
this is the JSX where handleChangeScore() is used:
this.state.objData .map((v,index)=>(
<tr>
<td>{index+1}</td>
<td>{v.data.id} - {v.data.name}</td>
<td><input type="text" name={v.data.id} className="form-control" onChange={(e)=>handleChangeScore(e,"q1",v.data.id)} defaultValue={(v.score.q1) ? v.score.q1 : 0} /></td>
<td><input type="text" name={v.data.id} className="form-control" onChange={(e)=>handleChangeScore(e,"q2",v.data.id)} defaultValue={(v.score.q2) ? v.score.q2: 0} /></td>
</tr>
))
The problem is when i use destructor to change the value on multiple object with specific key its not work or not change the value. Can anyone help me to fix my code ? Here’s the full code in codesanbox
>Solution :
Few things to be fixed
-
Your
item.data.idis number ande.target.nameis string. To compare them without type comparison use!=instead of!==. -
The
elseblock should be corrected as below.
handleChangeScore = (e, type, id) => {
const cScore = e.target.value;
this.setState((state) => {
return {
...state,
objData: state.objData.map((item) => {
if (item.data.id != e.target.name) return item;
else {
return { ...item, score: { ...item.score, [type]: cScore } };
}
})
};
});
};