1

I'm building an app in react native and I want a way in which I can regularly add a field to one ore all of the user data before pushing it to the database, It is an array of objects and I know the index of each object. I'm aware of object destructuring but I don't know how to go about this. In the example below, how do I add the field "hobby" and a value of "Football" to smith alone? Thanks in advance.

const [usersData, setUsersData] = useState([
  {
    name: "Jane",
    sex: "female",
    age: "20",
  },
  {
    name: "Doe",
    sex: "male",
    age: "29",
  },
  {
    name: "Smith",
    sex: "male",
    age: "24",
  },
]);

const addHobby = (index, hobby) => {
  //Adding the field here//
};
Anurag Srivastava
  • 14,077
  • 4
  • 33
  • 43
Johndev247
  • 91
  • 6

1 Answers1

1

Here's a way to achieve this:

const addHobby = (index, hobby) => {
  let temp = [...usersData] // Create a copy with the spread operator
  temp[index].hobby = hobby // Set new field
  setUsersData(temp) // Save the copy to state
}

...

addHobby(2, "Football") // 2 being known index of "Smith"

Edit: As suggested by @EmileBergeron, the spread operator creates a shallow copy only, which means the original state will still be mutated in case of object property changes. A more react friendly approach would be to use .map()

const addHobby = (index, hobby) => {

  // Create a copy using .map()
  const temp = usersData.map((data, idx) => {
    let tempData = {...data} // Copy object
    if(idx === index) tempData.hobby = hobby // Set new field
    return tempData
  }) 
  
  setUsersData(temp) // Save the copy to state
}
Anurag Srivastava
  • 14,077
  • 4
  • 33
  • 43