Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to set multiple object value with special key on react js

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

  1. Your item.data.id is number and e.target.name is string. To compare them without type comparison use != instead of !==.

  2. The else block 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 } };
          }
        })
      };
    });
  };

Code Sandbox

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading