Skip to content

Commit 00cbd61

Browse files
committed
Fixed favoriting of items in the list
1 parent 9c8c112 commit 00cbd61

File tree

1 file changed

+32
-5
lines changed

1 file changed

+32
-5
lines changed

RecipeFinder/src/components/RecipeCard.jsx

Lines changed: 32 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,41 @@
11
import styles from "../styles/RecipeCard.module.css";
22
import "../../node_modules/font-awesome/css/font-awesome.css";
3-
import { useState } from "react";
3+
import { useEffect, useState } from "react";
44
import { useSelector } from "react-redux";
55

66
const RecipeCard = () => {
7-
const [isFavorite, toggleFavorite] = useState(false);
87
const { meals } = useSelector(({ search }) => search);
8+
const [isFavorite, toggleFavorite] = useState([]);
9+
10+
/**
11+
* *Updates the isFavorite array whenever the meals array change (due to a new search query)
12+
*/
13+
useEffect(() => {
14+
if (meals === null) toggleFavorite([]);
15+
else toggleFavorite(() => new Array(meals.length).fill(false));
16+
}, [meals]);
17+
18+
console.log(isFavorite);
19+
20+
/**
21+
* *Toggles the favorite status at the respective index of clicked card.
22+
* @param {number} index
23+
*/
24+
const toggleFavoriteStatus = (index) => {
25+
/**
26+
* *This alters the favorited state onclick of the respective card. It uses the previous state snapshot and alters the particular index of the clicked card item.
27+
* @param(array) prevState
28+
*/
29+
toggleFavorite((prevState) => {
30+
return prevState.map((value, valIndex) =>
31+
valIndex === index ? !value : value
32+
);
33+
});
34+
};
935

1036
return (
1137
meals &&
12-
meals?.map((meal) => {
38+
meals?.map((meal, mealIndex) => {
1339
let ingredientsKeyNames = [];
1440
let quantityKeyNames = [];
1541

@@ -25,11 +51,12 @@ const RecipeCard = () => {
2551

2652
<i
2753
className={"fa fa-heart ".concat(
28-
`${isFavorite ? styles.red : ""}`
54+
`${isFavorite[mealIndex] ? styles.red : ""}`
2955
)}
30-
onClick={() => toggleFavorite((prevState) => !prevState)}
56+
onClick={() => toggleFavoriteStatus(mealIndex)}
3157
></i>
3258
</div>
59+
3360
<div className={styles.recipe_container}>
3461
<img src={meal.strMealThumb} alt="food_image" />
3562
<div className={styles.recipe_meta}>

0 commit comments

Comments
 (0)