armadiazrino

Untitled

Jun 22nd, 2022
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.13 KB | None | 0 0
  1. const bookmark = () => {
  2. // Getting bookmark item
  3. AsyncStorage.getItem('bookmark')
  4. .then(data => {
  5. // Parsing the value into JSON, since AsyncStorage data need to be a string
  6. const parsedData = JSON.parse(data);
  7. console.log('parsedData', parsedData);
  8. // Checking if there is any data
  9. if (parsedData?.length > 0) {
  10. // Grabbing the result by movie id
  11. const result = parsedData.find(item => item.id === movieDetail.id);
  12. console.log('result', result);
  13. // If the result is empty, then we can assume the movie hasn't bookmarked yet
  14. if (result === undefined) {
  15. // Trying to add the data (bookmark)
  16. parsedData.push(movieDetail);
  17. // Saving the data to the AsyncStorage,
  18. // We're using stringify to convert the object into string so it can be saved
  19. AsyncStorage.setItem('bookmark', JSON.stringify(parsedData))
  20. .then(_ => setIsBookmarked(true))
  21. .catch(error => console.log('failed to bookmark 1', error));
  22. console.log('saving bookmark');
  23. } else {
  24. // If data is exist, then we want to remove the bookmark
  25. console.log('data already exist, removing bookmark');
  26. // Getting the new data by using filter, excluding the movie by movie id
  27. const newData = parsedData.filter(
  28. item => item.id !== movieDetail.id,
  29. );
  30. // Saving the data to the AsyncStorage,
  31. AsyncStorage.setItem('bookmark', JSON.stringify(newData))
  32. .then(_ => setIsBookmarked(false))
  33. .catch(error => console.log('failed to bookmark 1', error));
  34. }
  35. } else {
  36. // If there's no data whatsoever, we 're trying to save it without needing to get any data
  37. AsyncStorage.setItem('bookmark', JSON.stringify([movieDetail]))
  38. .then(_ => setIsBookmarked(true))
  39. .catch(error => console.log('failed to bookmark 2', error));
  40. }
  41. })
  42. .catch(error => console.log('bookmark error', error));
  43. };
Advertisement
Add Comment
Please, Sign In to add comment