Home > front end >  How do I change the state of an array of objects in React?
How do I change the state of an array of objects in React?

Time:03-25

I'm trying to change the state of an array containing an object whenever something is typed inside of an input. The state of the array I'm trying to change looks like this:

const defaultCV = {
personalInfo: {
firstName: "",
lastName: "",
title: "",
about: "",
},
education: [
{
  id: uniqid(),
  university: "",
  city: "",
  degree: "",
  subject: "",
  from: "",
  to: "",
},
],

Specifically, I want to change the state of the 'education' section. My current, non-working code looks like this:

const handleEducationChange = (e) => {
setCV((prevState) => ({
  ...prevState,
  education: [
    {
      ...prevState.education,
      [e.target.id]: e.target.value,
    },
  ],
}));
};

When I type in the input and the function is triggered, I get the error "Warning: Each child in a list should have a unique "key" prop." I've been trying to make this work for the past few hours, any help as to what I'm doing wrong would be appreciated.

CodePudding user response:

You are destructuring an array in to an object that will not work

    education: [{ // this is the object you are trying to restructure into
      ...prevState.education, // this here is an array in your state
      [e.target.id]: e.target.value,
   }, ],
 }));

CodePudding user response:

Are you using the Array.map() method to render a list of components? That is a common cause of that error. For example if you are mapping the education array.

You can fix by using the object id as the key since that is already generated for each object:

defaultCV.education.map(institution => {
     return <Component key={institution.id} institution={institution} />
}
  • Related