I am trying to implement wishlist feature in reactjs, how do we check if clicked product is already in the wishlist array, here is my addToWishlist function, what logic am i missing here?
const addToWishlist = (id) => {
const check_wishlist = products.findIndex((item) => item.id === id);
console.log(check_wishlist);
if (check_wishlist !== -1) {
wishlist.push({ ...products.find((item) => item.id === id) });
setWishlist([...wishlist]);
} else {
wishlist.filter((item) => item.id !== id);
setWishlist([...wishlist]);
}
console.log(wishlist);
};
You have 2 error in your code 1: You should not push direct to wishlist 2: wishlist.filter not change value of wishlist
const addToWishlist = (id) => {
const check_wishlist = wishlist.find((item) => item.id === id);
if (!check_wishlist) {
const product = products.find((item) => item.id === id);
setWishlist([...wishlist, product]);
} else {
setWishlist(wishlist.filter((item) => item.id !== id));
}
console.log(wishlist);
};
Array.filter always returns new list, so you need to set the new list not the wishlist.
const addToWishlist = (id) => {
const check_wishlist = wishlist.findIndex((item) => item.id === id);
console.log(check_wishlist);
if (check_wishlist !== -1) {
setWishlist([
...wishlist
products.find((item) => item.id === id);
]);
} else {
const newList = wishlist.filter((item) => item.id !== id);
setWishlist(newList);
}
console.log(wishlist);
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.