How to Update Nested Array with Hooks in React
In this lesson, we will see how to update nested array with hooks in React, let's assume that we have an array of users and each user has an array of hobbies and we want to update the hobbies of a selected user.
Update the hobbies of a selected user
To do that check the code below:
const [users, setUsers] = useState([
{
id: 1,
name: 'john',
hobbies: [
{
id: 1,
name: 'sport'
},
{
id: 2,
name: 'cinema'
},
{
id: 3,
name: 'music'
},
]
},
{
id: 2,
name: 'mark',
hobbies: [
{
id: 1,
name: 'soccer'
},
{
id: 2,
name: 'hiking'
},
{
id: 3,
name: 'swimming'
},
]
}
]);
//update the hobbies of a selected user
const updatedUsers = [...users];
const user = updatedUsers.find(user => user.id === 2);
user.hobbies = user.hobbies.map(item => item.id === 1 ? {...item, {name: 'vlogging'}} : item);
setUsers(updatedUsers);