Save the ID of the image clicked in the cookie session in Next Js

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-cookie library is used to store the image.id when the image is clicked in handleImageClick.
  • The cookie is set with the key "clickedImageId", and it will expire after 7 days

Leave a comment

Your email address will not be published. Required fields are marked *