3

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)
    }
}

2 Answers 2

13

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));
  });
Sign up to request clarification or add additional context in comments.

3 Comments

I get " Possible Unhandled Promise Rejection (id: 0): TypeError: JSON.parse(contacts).concat is not a function. (In 'JSON.parse(contacts).concat(con)', 'JSON.parse(contacts).concat' is undefined) "
Updated my answer.
await AsyncStorage.getItem('contacts') ?
1

Get and set your records into an array then save to AsyncStorage:

saveContacts = async () => {
    try {
        let con = {
            roomId: this.state.roomId,
            nickname: this.state.nickname,
        }
        const contacts = await AsyncStorage.getItem('contacts') || '[]';
        contacts = JSON.parse(contacts);
        contacts.push(con);
        AsyncStorage.setItem('contacts', JSON.stringify(contacts)).then(() => {
            console.log('Contacts updated.')
        });
    } catch(error) {
        alert(error)
    }
};

5 Comments

I get " [TypeError: contacts.push is not a function. (In 'contacts.push(con)', 'contacts.push' is undefined)] "
This probably means that your assigning something other than an array to contacts. make sure the AsynStorage item 'contacts' is indeed an array and this will work.
Isn't contacts supposed to be that const variable? By the way I had to change it to let variable because if it's constant you cant do the 2 lines beneath.
Contacts is the variable and should be an array before you push anything to it. Otherwise, you'll end up with the error you are getting. It's the same reason the answer below is failing. I would log const contacts = await AsynStorage.getItem('contacts') and see what it returns.
@jkhedani Hey, If I wanna just log the RoomID when i getItem from Storage, How to handle that?

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.