Skip to content

Instantly share code, notes, and snippets.

@francisngo
Last active December 28, 2017 20:53
Show Gist options
  • Save francisngo/622c22ad9563c37d8c6cfddd665c8f8d to your computer and use it in GitHub Desktop.
Save francisngo/622c22ad9563c37d8c6cfddd665c8f8d to your computer and use it in GitHub Desktop.
Display Random Users and Submit a Post using Vanilla JS, Fetch API & Promises
const ul = document.getElementById('users');
const url = 'https://jsonplaceholder.typicode.com';
// Create the type of element you pass in the parameters
function createNode(element) {
return document.createElement(element);
}
// Append the second parameter(element) to the first one
function append(parent, el) {
return parent.appendChild(el);
}
// Get the first 10 users from JSONPlaceholder API
function fetchUsers() {
fetch(`${url}/users`)
.then((response) => response.json())
.then(function(data) {
let users = data;
return users.map(function(user) {
let li = createNode('li'),
p = createNode('p');
p.innerHTML += `Name: ${user.name} `;
p.innerHTML += `Email: ${user.email}`;
append(li, p);
append(ul, li);
})
})
.catch((error) => console.log(error));
}
// Submit a post to JSONPlaceholder API
function submitPost(event) {
event.preventDefault();
let title = document.getElementById('title').value;
let body = document.getElementById('body').value;
fetch(`${url}/posts`, {
method: 'POST',
body: JSON.stringify({
title: title,
body: body
}),
headers: {
'Content-type': 'application/json; charset=UTF-8'
}
})
.then((response) => response.json())
.then((data) => console.log(data))
.catch((err) => console.log(JSON.stringify(error)));
}
document.getElementById('getUsers').addEventListener('click', fetchUsers);
document.getElementById('postData').addEventListener('submit', submitPost);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment