I want to implement add-to favorite list functionality. But It only works on a single item I need multiple items. I use useRef Hook and use this npm package react-use-localstorage
The problem is my local storage doesn't work properly as I expected. It always updates a single item but I need it as an Array i.e [1, 2, 4, 7, 10]
If I reload my page only 3 number id will fill the heart
import React, { useRef } from "react";
import FavoriteBorder from "@mui/icons-material/FavoriteBorder";
import Favorite from "@mui/icons-material/Favorite";
import IconButton from "@mui/material/IconButton";
import useLocalStorage from 'react-use-localstorage';
const Fv = ({ id }) => {
const [storageItem, setStorageItem] = useLocalStorage(
"favourites",
JSON.stringify([])
);
//const storagedArray = useRef(JSON.parse(storageItem));
//const isFavourited = storagedArray.current.includes(id);
const isFavourited = storageItem.includes(id)
const handleToggleFavourite = () => {
if (!isFavourited) {
setStorageItem(JSON.stringify([...JSON.parse(storageItem), id]));
} else {
setStorageItem(
JSON.stringify(
JSON.parse(storageItem).filter((savedId) => savedId !== id)
)
);
}
return (
<IconButton onClick={handleToggleFavourite}>
{isFavourited ? <Favorite color="error" /> : <FavoriteBorder color="error" />}
</IconButton>
);
};
export default Fv;
Assign Component
<Fv id={product.id} />
