2

I have this function:

setNotActiveWalletsList = () => {
   
    const { GetAccounts } = this.props;
    let shallowCopyOfWalletsArray = [...GetAccounts]  
    const notActive = shallowCopyOfWalletsArray.filter(user => user.active !== true);


    let newArr = notActive.map(item => {

      return decryptAccountInformation(item).then(result => {
          !result.address ? null : item.address = result.address
      })
   
    });

    this.setState({ onlyNotActive: newArr });
  }

GetAccounts is an array of objects

The issue is, One of my colleagues have told me that I am mutating the array with this line:

 !result.address ? null : item.address = result.address

But I don't really understand why is this considered a mutation? I am sure I created a copy of the original array and modified it.

Any suggestions on how to resolve this, please?

Pejman Kheyri
  • 4,044
  • 9
  • 32
  • 39
user14587589
  • 449
  • 3
  • 19

1 Answers1

2

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 => {

      return decryptAccountInformation(item).then(result => {
          return !result.address ? item : {...item, address: result.address}
      })
   
    });
    Promise.all(promises).then(newArr => this.setState({ onlyNotActive: newArr }));
    
  }
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400