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

129
Visualizações
How to ensure fetch GET request runs after database updated?

I am having trouble ensuring that my GET request in Javascript runs after my PUT.

Sometimes the JSON promise returns with updated data sometimes it does not!

It appears to be random. It always displays correctly upon page reload.

I am getting a "Fetch failed loading: PUT" error in my console despite the database being updated successfully.

I know of await/async but was unclear if this was my solution and if so how I would implement with the correct syntax.

Here is my JS:

function like(id) {

    like_button = document.getElementById(`like-button-${id}`);
    
    if (like_button.style.backgroundColor == 'white') {
        fetch(`/like/${id}`, {
            method:'PUT',
            body: JSON.stringify({
                like: true
            })
        });

        like_button.style.backgroundColor = 'red';
    }
    else {
        fetch(`/like/${id}`, {
            method:'PUT',
            body: JSON.stringify({
                like: false
            })
        });

        like_button.style.backgroundColor = 'white';


    }

    fetch(`/like/${id}`)
    .then(response => response.json())
    .then(post => {
        like_button.innerHTML = post.likes;
    });

}

In case it is helpful here is my view in views.py:

@csrf_exempt
def like(request, id):
    post = Post.objects.get(id=id)
    user = User.objects.get(username=request.user.username)

    if request.method == "GET":
        return JsonResponse(post.serialize(), safe=False)

    if request.method == "PUT":
        data = json.loads(request.body)
        print(data.get("like"))
        if data.get("like"):
            post.Likes.add(user)
        else:
            post.Likes.remove(user)
        post.save()
        return HttpResponse(status=204)

Console error message

about 4 years ago · Juan Pablo Isaza
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