Working on "Edit" feature for project4 network.

I wrote a javascript function with two fetch. First one to update the post. Second one to retrieve the now updated post and show it on page (without the need to refresh the page).

Due to the async nature (?) of javascript, the second fetch is executed before the first fetch completes. So I had to add a time delay (with setTimeout). This works according to specification now. But I feel like there must be a smarter/more correct way to do this? Can anyone shed some light on this?

My code is:

function save_edits(id) {
  // PUT method to update the post
  fetch('/post/' + id, {
    method: 'PUT',
    body: JSON.stringify({
      post: document.querySelector('#textarea-' + id).value

  // GET method to retrieve the updated post and update DOM
  setTimeout(function() {
    fetch('/post/' + id)
      .then(response => response.json())
      .then(post => {

        document.querySelector('#post-' + id).innerHTML = ` ${post.post} `

        // append edit button
        const element = document.createElement('button');
        element.classList.add("btn", "btn-secondary", "btn-sm")
        element.innerHTML = "edit"

        element.addEventListener('click', function() {
          console.log('This element button has been clicked!')
        document.querySelector('#post-' + id).append(element)
  }, 100)
  • do you need the GET fetch? Isn't the contents of the updated post already in the DOM? (#textarea) Nov 24 '21 at 20:09
  • You are right. Technically I don't need the GET fetch. But I thought it would be more correct/robust if I loaded it with a GET fetch to ensure it was updated correctly in the first place.
    – dogchow
    Nov 26 '21 at 0:45

You must log in to answer this question.

Browse other questions tagged .