-3

I have this variable test1 = [], I push some res.json to it. I expect it to be something like this [[{json,json}]], but turns out it gives me undefined when I try to iterate it like this test1[0]. Can someone explain to me how is test1[0] undefined? And how can I get values from it?

Below is the chrome console output for this variable. enter image description here

snippet: test1 = data_array

var data_array = []
const BookingHistory = getBookings(userDbID).then((json) => {data_array.push(json)})

console.log("test1", data_array[0]) //undefined

getBookings:

export const getBookings = (userDbId) => {
    const id = userDbId; //one of the global state that is sent to Date from App
  
    // Create our request constructor with all the parameters we need
    const request = new Request(`/users/${id}/bookings`)

    return fetch(request)
        .then((res) => {
        if (res.status === 200) {
          return res.json();
        }
        })
        .then((json) => {return json})
      .catch((error) => {
        console.log(error);
      });
}
  • See [Is Chrome's JavaScript console lazy about evaluating arrays?](https://stackoverflow.com/questions/4057440/is-chromes-javascript-console-lazy-about-evaluating-arrays) (the array is empty when you try to access it in code.) – Guy Incognito Aug 12 '20 at 10:14
  • 4
    Add a snippet rather than a photo – Alexandre Elshobokshy Aug 12 '20 at 10:15
  • A snippet is the minimum code needed to reproduce. Create a simple array, console.log his first values (as you're doing), and show the exact problem. Learning how to create snippet will really help you onwards. You can create a snippet by clicking on edit, and then the `<>` button. – Alexandre Elshobokshy Aug 12 '20 at 10:26

1 Answers1

1

The fetch() function is asynchronous. It returns a Promise, meaning that its return value is not evaluated immediately. If you want to use its return value, you must do it in the handler function (or you use async/await syntax). You could modify your code like so:

let data_array = []
const BookingHistory = getBookings(userDbID).then((json) => {
  // This only runs after response from fetch request arrives. Not immediately
  data_array.push(json);
  console.log(data_array[0]);  // Correct value this time, data_array is no longer an empty array
  ... // The rest of the code that makes use of the updated value of data_array variable
})

console.log("test1", data_array) // This evaluates data_array immediately so, at this point, data_array is still an empty array
JayCodist
  • 2,424
  • 2
  • 12
  • 28