Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

87
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!