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

186
Views
With JS fetch-PUT i update my db (and it does indeed) but with fetch-GET it displays the data just before the update

Im working on a Django project kind of network. I have a JS code in which with a fetch-PUT i update my db and i can check from the file that it is updated.

function update_like(identity) {
    fetch('/like',{
        method: 'PUT',
        body: JSON.stringify({
            id: identity,
        })
        
    },
    show(identity)
    )
};

And then with a fetch-GET i try to retrieve the data

function show(identity) {
    fetch('/like', {
        headers: {
          'Cache-Control': 'no-cache'
        }
      })
    
      .then(response => response.json())
      .then(likedic => {
          console.log(likedic);
        if (likedic[identity]){
            document.getElementById(`arithmos${identity}`).innerHTML = ` ${likedic[identity].length}`;
        } else {
            document.getElementById(`arithmos${identity}`).innerHTML =' 0';
        } 
      }); 
}

the thing is, that every time, it displays the data from the just previous updated db.

I mean first time i run update_like function, the show function diplays the db as it was before update_like function runs. But i can see from the file that db is updated.

Second time i run update_like function the show function diplays the db as it should be the first time, even if i can see again from the file that db is updated etc.

I suppose that it doesn't have enough time to read the update db. I have tryied so many things but i cant make it work. Underneath is my python function

def like(request):
    likedic = {}
    if request.method == 'GET':
        allcomments = Like.objects.all()
        for i in range(len(allcomments)):
            if allcomments[i].comment.id not in likedic.keys():
                likedic[allcomments[i].comment.id] = []
                likedic[allcomments[i].comment.id].append(allcomments[i].user.username)
                print('likedic',likedic)
            else:
                likedic[allcomments[i].comment.id].append(allcomments[i].user.username)
        return JsonResponse(likedic, safe=False)
    elif request.method == "PUT":
        data = json.loads(request.body)
        Likes = Like.objects.filter(comment = Comment.objects.get(id = data['id']), user = User.objects.get(username = request.user.username))
        if Likes:
            Likes.delete()
        else:
            Likes = Like(comment = Comment.objects.get(id = data['id']), user = User.objects.get(username = request.user.username))
            Likes.save()
        return HttpResponse(status=204)

        # Email must be via GET or PUT
    else:
        return JsonResponse({
            "error": "GET or PUT request required."
        }, status=400)

I would really apreciate some advise. Thanks so much in advance.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Use async functions instead of regular functions, and await the completion of the first function before performing the 2nd. For example, convert update_like to an async funciton.

Later, call show only after awaiting update_like:

// `await` must be used within an async fucntion
// So, I'll use await inside this immediately invoked function: 
(async function()
{
    let identity = "someIdentity";
    await update_like(identity); // Waits until update is complete 
    return show(identity);
})();
about 4 years ago · Juan Pablo Isaza Report

0

I finally found a solution! I added a setTimeout function before I call show function. I set 0.05sec and it works! I dont know if this is the right or the best way to do it but it finally works!

function update_like(identity) {
    fetch('/like',{
        method: 'PUT',
        body: JSON.stringify({
            id: identity,
        })
        
    },
    setTimeout(() => {
        show(identity);
      }, 50)
    )
};
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!