How to get the id dynamically to store cookies

If you want the ID of the current post outside of the loop, you can use get_queried_object_id(). Just make sure to check is_singular() first, or you could end up storing IDs of things other than posts. This could cause problems if there’s overlap with post IDs. I’d share the amended code with those changes, but for some reason you posted a screenshot instead of code, and I’m not writing it out by hand.