I have created a like button in HTML that allows a user to like a post by using JSON. I want every user to only be able to like and unlike once (I don't want them to be able to go to another page then return and like the page again). I am trying to do this by using localStorage
, but it is only doing the condition in the else statement.
JavaScript:
var liked = false;
if(!localStorage.getItem('liked')){
localStorage.setItem('liked', false);
}
function like(id){
console.log("like button is clicked");
let likes = Number(document.querySelector(`#likes_num_${id}`).innerText);
console.log(likes);
let liked = localStorage.getItem('liked');
if(liked === false){
let likeNum = likes +=1;
//like the post
fetch(`/like/${id}`,{
method: 'PUT',
body: JSON.stringify({
likes: likeNum
})
})
localStorage.setItem('liked', true);
}else{
console.log("should be unliking");
let likeNum = likes -=1;
//unlike the post
fetch(`/like/${id}`,{
method: 'PUT',
body: JSON.stringify({
likes: likeNum
})
})
localStorage.setItem('liked', false);
}
//display the post
setTimeout(()=>{
fetch(`/like/${id}`)
.then(response => response.json())
.then(post => {
let likes = document.querySelector(`#likes_num_${id}`);
likes.innerHTML = `${post.likes}`
})
}, 100)
}