2

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.

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

4 Comments

Ok, still a little problem. If there array is completely empty at the beginning, I get this error [Unhandled promise rejection: TypeError: null is not an object (evaluating 'arr.push')]
you can do something like arr ? arr.push(ProdID): [];
hope it helps , feel free for doubts
Thanks. It only works if I do it like this: arr ? arr.push(ProdId) : (arr = [ProdId]); Only problem left ist, to check if ProdId is already in arr so that it does not get pushed into the array.

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.