Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

155
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda