Keselme
Keselme

Reputation: 4249

setState of an empty array

I'm working on a code where I have an empty array which has to be filled after a certain request returns.

I tried to setState of the array like that:

const [recentTransactionContacts,setRecentTransactionContacts] = useState<object[]>([])
///// more code

Contacts.getAll((err, contacts) => {
       if(err) throw err
                    
       if(contacts.length > 0)
           setRecentTransactionContacts(prevState => ({...prevState.recentTransactionContacts, ...contacts}));
       else 
           ToastAndroid.show(`There no contacts on your phone. Can't transfer`, ToastAndroid.SHORT) 
})

Now, I don't see any change in the array of contacts after trying to do setState that way. The only way, that I could update the state was like that:

setRecentTransactionContacts(contacts)

However, I don't think that the latter is the correct way.

What is the correct way to update the state of an array?

Upvotes: 0

Views: 758

Answers (2)

Yashank
Yashank

Reputation: 813

Using prevState or updater function is required in cases where the current state might be changed or stale, which doesn't seem to be the case here. Infact it could be the prevState itself causing issues, as the prevState value could be undefined at run.

As stated, replace your method to setRecentTransactionContacts([...recentTransactionContacts, ...contacts]); which will take in the current state value and append the contacts to the state.

Upvotes: 1

thelonglqd
thelonglqd

Reputation: 1862

I think this should be served your case, the recentTransactionContacts is not changed after this line runs so you do not need to access to prevState to do what you want.

setRecentTransactionContacts([...recentTransactionContacts, ...contacts]);

Upvotes: 1

Related Questions