Install js-cookie: Run this command in your project to install js-cookie:
npm install js-cookie
Import js-cookie into your component.
Set a cookie when an image is clicked.
const handleImageClick = async (image) => {
try {
const updatedViewCount = image.viewCount + 1;
// Set a cookie when an image is clicked
Cookies.set("clickedImageId", image.id, { expires: 7 }); // Set the cookie to expire in 7 days
await fetch(`http://localhost:3000/api/assigned-collections/${image.collectionId}`, {
method: "PATCH",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
assignedcollections: data.map((col) =>
col.id === image.id
? { ...col, viewCount: updatedViewCount }
: col
),
}),
});
setData((prevData) =>
prevData.map((col) =>
col.id === image.id ? { ...col, viewCount: updatedViewCount } : col
)
);
} catch (error) {
console.error("Failed to update view count:", error);
}
};
- The
js-cookielibrary is used to store theimage.idwhen the image is clicked inhandleImageClick. - The cookie is set with the key
"clickedImageId", and it will expire after 7 days