Skip to content
Advertisement

Toggle Color of Button Added To Favorites in React

I’m displaying a list of items and user has ability to add an item to their Favorites.

My issue is that I’m only capturing one favorite state, thus, on click of one button, all of the item buttons (red heart below) change color.

enter image description here

I’m trying to work through the best way to handle the toggling of a favorite item.

Here’s the button code and the corresponding click handler:

<Table.Cell textAlign="center">
                    <Button
                      onClick={() => addFavorite(card, props.loggedUser)}
                      bordered
                      color={favorite ? "google plus" : "twitter"}
                      icon={favorite ? "heart" : "heart outline"}
                    />
                  </Table.Cell>

 const addFavorite = (card, user) => {
    console.log("CARD + USER ON CLICK", card, user);
    props.updateUser(card, user);
    setFavorite(!favorite);
  };

On click, i’m sending the favorite to the user’s favorite array in database and this works successfully. (although I’m not handling any removal yet).

I also, set the state as shown with the setFavorite call above, however this is just tracking one universal ‘favorite’ state and not the favorite state for each item.

const [favorite, setFavorite] = useState("false");

What would be the best way to go about doing this. Should i be adding a state that holds all of the favorites?

I do have a store/state available called loggedUser which contains all of the user’s information and favorite items. Should i be running a check against that maybe?

Thanks for any help on this.

Advertisement

Answer

Well, as you mentioned in above answer, to keep the data even you refresh the page, you should save the favorite array in localstorage.

const [favorites, setFavorite] = useState("");

useEffect(async ()=>{
  let savedFavorite = await localStorage.getItem('__Fav');
  if(savedFavorite) {
    setFavorite(savedFavorite);
  }
}, [])

Inside addFavoirte you can check if the clicked one is already in favorite array. If it is in there you can just remove it and save the new favorite array to the localstorage. if it not in the favorite array you can just push it and save the new array to the localstorage again.

So now, if you reload the page useEffect will fetch the savedFavorite array and add it to the favorite array in the component.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement