Whenever I submit a post, I am unable to display them and I'm not sure why it's not working. The getPosts()
function works fine when I refresh the page. However, after submitting the posts, I can't seem to retrieve them. I am using a JSON fake server for the backend.
// On load
document.addEventListener('DOMContentLoaded', function () {
getPosts();
});
// Submit 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));
}
Below 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));
});
}