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

89
Vistas
API or JavaScript inconsistencies

I have a JS function in my template which works with fetch commands to relay to a Django view. The strange part is that it as expected most of the time but sometimes it just doesn't and I cannot figure out why.

JS in template:

<script>
    if (document.querySelectorAll(".nav-link")[1].innerHTML != "Log In") {
        var like = document.querySelector(".likes");
        var quantity = document.querySelector(".quantity");
        like.addEventListener("click", () => likes())
        function likes () {
            fetch(`/likes/${like.value}`, {
                method: "PUT"});
            if (like.innerHTML.slice(0, 2) != "Un") {
                like.innerHTML = "Unlike &#128148";
            }
            else {
                like.innerHTML = "Like &#10084";
            }
            fetch(`/likes/${like.value}`)
            .then(response => response.json())
            .then(post => {
                console.log(post["liked"]);
                quantity.innerHTML = post["liked"].length;
            });
        }
    }
</script>

my view:

@csrf_exempt
@login_required
def likes(request, id):
    user = User.objects.get(username=request.user)
    try:
        post = Post.objects.get(pk=id)
    except Post.DoesNotExist:
        return JsonResponse({"error": "No such post"}, status=404)
    
    if request.method == "GET":
        return JsonResponse(post.serialize())

    if request.method == "PUT":
        #data = json.loads(request)
        if user not in post.liked.all() and post.poster != user:
            print("adding")
            post.liked.add(user)
            post.save()
        else:
            print("removing")
            post.liked.remove(user)
            post.save()
        return HttpResponse(status=204)

It should be alternating between an empty list and a list which contains a two.

janky JS

However you can see that, although it usually works right, it has a spot where there are several "[2]" in a row and sometimes it has several "[]" in a row too.

Actually this only started after adding the second fetch but I can't understand why; before then it alternated without problems.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

As @Jared Smith said in comments there is no guarantee order of fetch as it is asynchronous, to control the order use async and await to wait for the result of response something like this:

    like.addEventListener("click", async () => await likes())
    async function likes () {
        await fetch(`/likes/${like.value}`, {
            method: "PUT"});
        if (like.innerHTML.slice(0, 2) != "Un") {
            like.innerHTML = "Unlike &#128148";
        }
        else {
            like.innerHTML = "Like &#10084";
        }
        await fetch(`/likes/${like.value}`);
        const post = await response.json();
        quantity.innerHTML = post["liked"].length;
    }
about 4 years ago · Juan Pablo Isaza Denunciar
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