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

130
Vistas
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 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