Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To modify a nested value within an array in React Native, you can use the spread operator and map function to create a new array with the updated value. Here's an example:

const [list, setList] = useState([
  { name: 'John', age: 25},
  { name: 'Jane', age: 30},
  { name: 'Bob', age: 35}
]);

const updateAge = (index, newAge) => {
  setList(prevList => prevList.map((person, i) =>
    i === index ? { ...person, age: newAge } : person
  ));
}

In this example, we have an array of objects called list. To update the age of a person at a specific index, we create a new array by using the map function and the spread operator. We check if the index of the current person matches the input index, and if it does, we update the age property with the new value. Otherwise, we return the original person without modifying it.

To call this function, we can pass in the index of the person we want to update and the new age value:

updateAge(1, 32); // Updates Jane's age to 32

This will update the list state with the new array that includes the updated value.