Fetch the URL
1window.addEventListener("load", function() {
2 fetch("https://handlers.education.launchcode.org/static/planets.json").then(function(response){
3 // TODO: do something after fetching and receiving a response
4 });
5});
Use the .json() method to print response data:
1fetch("https://handlers.education.launchcode.org/static/planets.json").then(function(response){
2 response.json().then(function(json) {
3 console.log(json);
4 });
5});
Your console.log
statement should return the same array of 6 JSON objects containing planetary data found here.
Capture the JSON data:
1window.addEventListener("load", function() {
2 let json = [];
3 fetch("https://handlers.education.launchcode.org/static/planets.json").then(function(response){
4 response.json().then(function(json) {
5 console.log(json);
6 });
7 });
8 const destination = document.getElementById("destination");
9 destination.innerHTML = `<h3>Planet ${json[0].name}</h3>`;
10});
We can tell that our fetch works because the JSON array is printed to the console.
However, you should also see an error in the console related to the template literal
using json[0].name
.
This error occurs because of the asynchronous nature of JavaScript. Although we
now have json
defined outside of the fetch request, at the point in time that
we seek it for the template literal, we haven't yet received the json data.
One clue that asynchronism is at play: the error appears before the printed JSON.
Dynamically change planet info displayed
1fetch("https://handlers.education.launchcode.org/static/planets.json").then(function(response) {
2 response.json().then(function(json) {
3 const destination = document.getElementById("destination");
4 let index = 0;
5 destination.addEventListener("click", function(){
6 destination.innerHTML = `
7 <div>
8 <h3>Planet ${json[index].name}</h3>
9 <img src=${json[index].image} height=250></img>
10 </div>
11 `;
12 index = (index + 1) % json.length;
13 });
14 });
15});