0

This is my first time attempting to fetch a local JSON file.

I've gotten the data into an array called "drinks" when I console log the array I can see all of the data from the JSON file, but when I try to use a higher order function it'll return an empty array. I'm doing this on my local live server, but I've also tried with the web server for chrome, I haven't noticed a difference.

let drinks=[];

fetch('./coldMenu.JSON', {
  headers : { 
    'Content-Type': 'application/json',
    'Accept': 'application/json'
   }
})
    .then(response=>response.json())
    .then(data=>drinks.push(...data.drinks))

    console.log(drinks)

   let coldMenuHtml= drinks.map(drink=>{
       ` <img src="${drink.img}" alt="${drink.drink}" class="im">`
    });

    console.log(coldMenuHtml)

The goal is to get the information from the JSON and use it to create a coffee menu. Before the menu is displayed there will be a box asking if they want to see the menu for hot or cold beverages, then I planned to fetch and put the information onto the page.

  • 1
    well you should be seeing an empty array when you do a `console.log` – Muhammad Usman Dec 21 '18 at 01:05
  • I've tried inserting into a div by setting the divs innerHTML= coldMenuHtml, that's not working either... –  Dec 21 '18 at 01:09
  • that's because `coldMenuHtml` is an array of `undefined` and that's not how you append the `html`. better look at my answer below for details – Muhammad Usman Dec 21 '18 at 01:29

2 Answers2

0

The fetch is async which is why data wont be available right after the last then. Add the logic inside the last then

To test

.then(data => {
    console.log(data)

    let coldMenuHtml= data.drinks.map(drink => {
     `<img src="${drink.img}" alt="${drink.drink}" class="im">`
    });

    console.log(coldMenuHtml)
 })
varoons
  • 3,807
  • 1
  • 16
  • 20
0

You are trying to loop on the data before it's available. The universal issue of most newbies when making async calls in JS so you better read this How to return response from an async call.

Now the second issue is, you are generating the html inside a map and not returning anything so you'll get an array of undefined. And that'll do nothing.

It would be easier if you just consider using a simple for loop to generate the html and keep appending to the div you want

For your code to fix it. Just move the code inside the last .then and it should work.

Something like

let drinks = [];

fetch('./coldMenu.JSON', {
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        }
    })
    .then(response => response.json())
    .then(data => {
        drinks = [...data.drinks];

        console.log(drinks)

        for (var i = 0; i < drinks.length; i++) {
            document.querySelector('selector').innerHTML += `<img src="${drinks[i].img}" alt="${drinks[i].drink}" class="im">`
        }


    })
Muhammad Usman
  • 10,039
  • 22
  • 39