Skip to content

Instantly share code, notes, and snippets.

@samuelguebo
Created March 31, 2018 22:01
Show Gist options
  • Save samuelguebo/5e55cb73645df161b199ead41582a432 to your computer and use it in GitHub Desktop.
Save samuelguebo/5e55cb73645df161b199ead41582a432 to your computer and use it in GitHub Desktop.
How to Use the JavaScript Fetch API to Get JSON Data
// ES6 compatibility
require("isomorphic-fetch")
// Set default api url
var apiUrl = 'https://randomuser.me/api/?results=10'
fetch(apiUrl).then(response => {
return response.json();
}).then(data => {
/**
* Work with JSON data here
* Loop through persons
*/
var persons = data.results
persons.forEach(function(person) {
// Echo person details
console.log(
"My name is %s and I am %s \n",
person.name.first + " " + person.name.last,
person.gender);
})
}).catch(err => {
// Do something for an error here
console.log(err)
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment