Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 633
waze Avatar asked Feb 18 '26 18:02

waze


1 Answers

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))
  })
like image 136
Yury Tarabanko Avatar answered Feb 20 '26 08:02

Yury Tarabanko



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!