0

I'd like to update a state of one object in array, not updating the state of whole array.

const [users, setUsers] = useState;

const data = [
{ 
    id: 1,
    name: "John",
    activeAccount: 1 
},
{ 
    id: 2,
    name: "Mary",
    activeAccount: 1 
},
{ 
    id: 3,
    name: "Max",
    activeAccount: 1 
}
]

For example, John deactivate his account and state of activeAccount should be updated to 0. So only one object should be updated (he has no data from other users and cannot update all array) - just example, why i use here user.id


const index = users.findIndex(obj => obj.id === user.id); // find index of object
users[index].activeAccount = 0
setUsers(users) // Nothing updated

I also tried to use Immutability Helper

import update from 'immutability-helper';

const index = users.findIndex(obj => obj.id === user.id); // find index of object
setUsers({
   users: update(...users, {index: {activeAccount: {$set: 0 }}})
})

Could anyone help? Is there a solution?

1
  • 1
    Hello I think this answer should help you. Commented Jan 15, 2020 at 22:38

2 Answers 2

2

Solution:

const index = users.findIndex(obj => obj.id === user.id);
setUsers([...users, users[index].activateAccount = 0])
Sign up to request clarification or add additional context in comments.

Comments

0

There might be a problem in calling

setUsers({
  users: update(...users, {index: {activeAccount: {$set: 0 }}})
})

In case you are initialising your state with:

const data = [
{ 
    id: 1,
    name: "John",
    activeAccount: 1 
},
{ 
    id: 2,
    name: "Mary",
    activeAccount: 1 
},
{ 
    id: 3,
    name: "Max",
    activeAccount: 1 
}
]

const [users, setUsers] = useState(data);

then you need to call setUsers without object:

setUsers(
  update(...users, {index: {activeAccount: {$set: 0 }}})
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.