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)