Search code examples
javascriptajaxasynchronouspostget

Ajax - can't display posts after i submit


After i submit a post i can't display them. i don't know why aren't working. The getPosts() function is working when i refresh the page, everything is ok. But after i submit the posts i can't get them. I am using JSON fake server for the backend.

// On load
document.addEventListener('DOMContentLoaded', function () {
  getPosts();
});

// Sumbit post
document.querySelector('#wrapper-form').addEventListener('click', submitPost);

// Function Helpers
function submitPost(e) {
 if(e.target.dataset.role === 'submit-post') {
   http.submitPost();
   getPosts();
}

 e.preventDefault();
}

// Get posts
function getPosts() {
 http.getPosts()
   .then(response => {
     ui.populateList(response);
  })
   .catch(err => console.log(err));
 }

And here are the requests:

// Get
getPosts() {
  return new Promise((resolve, reject) => {

  this.xhr.open('GET', 'http://localhost:3000/posts', true);

  this.xhr.onload(
   const response = JSON.parse(this.xhr.responseText);

    if(this.xhr.status === 200 && this.xhr.readyState === 4) {
     resolve(response);
    } else {
     reject('Some Error' + status);
    }
 );

  this.xhr.send();
 });
}

// Submit
submitPost() {
  return new Promise((resolve, reject) => {
   const data = {
    title: document.querySelector(UiSelectors.titleInput).value,
    body: document.querySelector(UiSelectors.bodyInput).value
   };

  this.xhr.open('POST', 'http://localhost:3000/posts', true);

  this.xhr.setRequestHeader('Content-type', 'application/json;charset=UTF-8');

  this.xhr.send(JSON.stringify(data));
 });
}

Solution

  • I figured out:

    http.submitPost()
     .then(response => {
       getPosts();
    });
    

    Apparently my newbie programmer skills didn't know that you can't have 2 requests at the same time. So i need it to first submit, and after i submited then get the posts.

    First i did:

    function submitPost(e) {
     if(e.target.dataset.role === 'submit-post') {
       // I did 2 requests as the same time. That was the problem
       http.submitPost();
       getPosts();
    }
    
     e.preventDefault();
    }