Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save an array of Items in AsyncStorage

How can I save an array of Items with AsyncStorage in react-native? So that every time you add another contact to your list it keeps adding up and not rewriting

Code:

saveContacts = ()=> {
    try {
        let con = {
            roomId: this.state.roomId,
            nickname: this.state.nickname,
        }
        AsyncStorage.setItem('contacts', JSON.stringify(con));
    }catch(error) {
        alert(error)
    }
}
like image 856
I'm not human Avatar asked Nov 25 '25 00:11

I'm not human


1 Answers

You can retrieve the contacts and concat the new contact to the list, then set it back into storage. Just make sure to initially set it as an empty array:

AsyncStorage.getItem('contacts')
  .then((contacts) => {
    const c = contacts ? JSON.parse(contacts) : [];
    c.push(con);
    AsyncStorage.setItem('contacts', JSON.stringify(c));
  });
like image 147
Matt Aft Avatar answered Nov 27 '25 14:11

Matt Aft



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!