Reactjs Array Mutation
I have this function: setNotActiveWalletsList = () => { const { GetAccounts } = this.props; let shallowCopyOfWalletsArray = [...GetAccounts] const notActive =
Solution 1:
Spread syntax just does a one level closing of the object or array. Any object or array which is more than one level deep will still have the same reference. Hence when you using notActive
array items
, you are essentially working on the same reference that was inside GetAccounts
The correct way to update is to return the cloned and updated reference from within the map function and using Promise.all
to also handle the async call
setNotActiveWalletsList = () => {
const { GetAccounts } = this.props;
let shallowCopyOfWalletsArray = [...GetAccounts]
const notActive = shallowCopyOfWalletsArray.filter(user => user.active !== true);
let promises = notActive.map(item => {
returndecryptAccountInformation(item).then(result => {
return !result.address ? item : {...item, address: result.address}
})
});
Promise.all(promises).then(newArr =>this.setState({ onlyNotActive: newArr }));
}
Post a Comment for "Reactjs Array Mutation"