hapfr
hapfr

Reputation: 93

Push to array with AsyncStorage

I'm trying to build a favourite system with AsyncStorage in React Native. On my ProductDetailScreen I have the corresponding ProdID available. I'd like to save the ProdID to AsyncStorage.

  const arr = [];
  const saveFavorites = async () => {
    arr.push(ProdID);
    await AsyncStorage.setItem("FAVORITES", JSON.stringify(arr));
  };

  const getFavorites = async () => {
    const favs = await AsyncStorage.getItem("FAVORITES");
    let parsedFavs = JSON.parse(favs);
    console.log(parsedFavs);
  };

This works. However if I go to the next Product and click the saveFavorites button, obviously the arr gets initiated with an empty array.

I can't wrap my head around how I would create the empty array if the saveFavorites button was never clicked before but push to the array if there is already an ID in it. I tried it with useState and useEffect but without success. Any help would be appreciated.

Upvotes: 2

Views: 1084

Answers (1)

Gaurav Roy
Gaurav Roy

Reputation: 12195

You can do like

const saveFavorites = async () => {
 let data = await AsyncStorage.getItem("FAVORITES");

let arr = JSON.parse(data);
    arr.push(ProdID);
    await AsyncStorage.setItem("FAVORITES", JSON.stringify(arr));
  };

try with this

Upvotes: 1

Related Questions