React Native AsyncStorage

2k views Asked by At

I want to save houses in an array using AsyncStorage. Each array element represents a house Object. And each house object has a latitude, longitude and a house number. I am not sure how to go about representing this. It seems to me that AsyncStorage is not well-suited for saving dynamic objects that can be updated programmatically. I want to be able to add more houses and delete some houses. Basically what I am trying to do is bookmark some houses and delete them from the bookmarks when the user clicks. Can anyone help ?

2

There are 2 answers

0
Dan On BEST ANSWER

AsyncStorage is absolutely perfect for this.

Starting with the structure of your houses, I would create an Array which stores objects representing an individual house.

const houses = [
  {
    number: 1,
    latitude: 51.5033,
    longitude: -0.119519
  }
]

Saving to AsyncStorage

When you want to write your collection to AsyncStorage, you would do so like this:

AsyncStorage
  .setItem('@houses', JSON.stringify(houses))
  .then(houses => console.log(houses)

static setItem(key: string, value: string, callback?: ?(error: ?Error) => void)

You can also use async/await if your project is set up to support it.

Reading from AsyncStorage

Reading your collection back from AsyncStorage is simply done via:

AsyncStorage
  .getItem('@houses')
  .then(houses => console.log(JSON.parse(houses)))

You could set the response in your state, do as you please.

Deleting a specific house

This depends entirely on how you set your app up. Are you going to map through each house and create a list component for example?

enter image description here

(Sorry about losing the border on the right)

If so, you could:

houses.map(house => (
  <View>
   <Text>Number: {house.number}</Text>
   <Text>Latitude: {house.latitude}</Text>
   <Text>Longitude: {house.longitude</Text>
   <Button onPress={() => this.deleteHouse(house.number)}/>
  </View>
));

Then create a deleteHouse function which will handle it.

const deleteHouse = (number) => {
  const { houses } = this.state; // Assuming you set state as previously mentioned
  const newHouses = houses.filter((house) => house.number != number);
  this.setState({houses: newHouses}, () => saveHouses);
}

And finally a saveHouses to sync it back to AsyncStorage. The function will clear AsyncStorage and then save the new houses.

const saveHouses = () => {
  const { houses } = state;
  AsyncStorage
    .removeItem('@houses')
    .then(() => {
      AsyncStorage
        .setItem('@houses', JSON.stringify(houses))
        .then(houses => console.log(houses)
    });
}
0
Estuardo Estrada On

You need a Sqlite alternative like Realm, it's free, fast and easy to code, with this you will save tons of hours of work, also as you need, you can make queries, update and delete objects.