Created
March 31, 2018 22:01
-
-
Save samuelguebo/5e55cb73645df161b199ead41582a432 to your computer and use it in GitHub Desktop.
How to Use the JavaScript Fetch API to Get JSON Data
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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