Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

88
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda