StelKizi
StelKizi

Reputation: 90

React localStorage issue

I have an app where I'm fetching data from an API and render it into cards. There are two pages, Home where the cards are rendered and Favorites where the cards that have been marked as favorites are rendered (each card has a heart icon that indicates whether it's favorite or not). There is an array where all the cards marked as favorites are being pushed, and I'm pushing this array into localStorage with this useEffect:

 useEffect(() => {
    localStorage.setItem('my-beer-list', JSON.stringify(favoriteBeers));
  });

The problem is that upon refresh, the Favorites page has kept the cards that were marked as such, but their corresponding cards at Home are not marked as favorite any more, and can be selected again resulting in duplicate cards in the other page.

The following function where checks if the card is "favorited" and then passed as prop to both the card and its corresponding modal

const isFavorite = (beer, favoriteBeers) => {
    return favoriteBeers.includes(beer);
  }

I have a codesandbox with the project here, in case you want to check it a bit more

Upvotes: 1

Views: 103

Answers (3)

Zia ur Rehman
Zia ur Rehman

Reputation: 565

Need to update favoriteBeers.map(fav => fav.id).includes(beer.id) part of your code

const isFavorite = (beer, favoriteBeers) => {
   return favoriteBeers.map(fav => fav.id).includes(beer.id);
}

And get 100% perfect result.

Upvotes: 1

Bart Krakowski
Bart Krakowski

Reputation: 1670

This is because you are trying to verify that the entire object exists. Instead, compare one of its fields (e.g. name or id if unique).

Let's replace the isFavorite function to:

const isFavorite = (beer, favoriteBeers) => {
  return favoriteBeers.some(e => e.name === beer.name)
};

Upvotes: 2

Felipe Araujo
Felipe Araujo

Reputation: 21

Since beer on your isFavorite method is an object, you can't verify if favoriteBeers, an array of objects, includes it.

So a way to do it could be:

const isFavorite = (beer, favoriteBeers) => {
  return favoriteBeers.find((favBeer) => favBeer.id === beer.id); 
}

This would return the object that has beer's id inside the favoriteBeers array or undefined if the id is not found.

Check here for more details: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find#find_an_object_in_an_array_by_one_of_its_properties

Upvotes: 1

Related Questions