Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

163
Views
How to use localStorage in JavaScript to keep track of a true/false variable?

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)
}
about 4 years ago · Santiago Gelvez
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!