0

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)
}
  • undefined <> false. undefined is falsy, not false. try to use == instead of === and see if that helps. – anthonyb Jul 21 '22 at 21:48
  • Boolean values are stored as strings in localStorage. So false is actually stored as "false". In your if statement just wrap false in quotes. – imvain2 Jul 21 '22 at 21:55
  • 1
    Local storage can **only** store strings. – connexo Jul 21 '22 at 21:58
  • First sentence in the documentation: [The keys and the values stored with localStorage are always in the UTF-16 string format, which uses two bytes per character. As with objects, integer keys are automatically converted to strings.](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage#description). Consider making basic docs checks. – connexo Jul 21 '22 at 22:14
  • @connexo, my application has multiple users. Is there any way to store the ```localStorage``` for particular users or something similar that will achieve the desired effect? – user19590524 Jul 23 '22 at 00:26

0 Answers0