Search code examples
javascriptreact-nativeasyncstorage

React Native AsyncStorage save multiple items


Is it possible to save multiple items with same key with AsyncStorage? I have a ListView with multiple item that can be added to favorites, when the user presses the 'add to favs' button it executes this code:

AsyncStorage.setItem("key", JSON.stringify(item.CodViatura));

But if I want to add another item, it will replace the previous one. How can I add more than one with the same key? So I can call this code on favorites screen:

AsyncStorage.getItem('key').then((cod)=>{
  this.setState({value: JSON.parse(cod)}
  });
})

I know I can use realm for data management but I found it harder than AsyncStorage.


Solution

  • Store array of items

    AsyncStorage
      .getItem('key')
      .then(favs => {
          favs = favs == null ? [] : JSON.parse(favs)
    
          favs.push(item.CodViatura)
    
          return AsyncStorage.setItem('key', JSON.stringify(favs))
      })