0

Here in the snippet below is my script to store in a single Array (const store) all the data that I need to exploit in a structured way. In order to use them "simply" afterwards.

console.log(store) displays in the console the desired data structure:

(2) [{…}, {…}]
0: {ID: "freecodecamp", streams: {…}, users: {…}, channels: {…}}
1: {ID: "funfunfunction", channels: {…}, users: {…}, streams: {…}}

console.log(store[0].ID) displays the desired result: "freecodecamp"

However store[0].users, store[0].channels, and store[0].streams outputs undefined.

I don't understand why. While everything works great with store[0].ID

const matchCharUrl = str => str.match(/[^/]/g).join('')

// Twitch.tv API call and settings
// --------------------------------------------------
const twitchAPI = () => {
  // const baseUrl = 'https://api.twitch.tv/kraken' // Twitch API base URL

  const baseUrl = 'https://wind-bow.glitch.me/twitch-api/' // FCC Twitch API Pass-through
  const params = ['users/', 'channels/', 'streams/'] // Twitch API, enabled root

  // suffix (channel or user) identifier
  const identifiers = ['freecodecamp', 'funfunfunction']

  // array with datas that will be exploit in a function ( displayResults() )
  const store = []

  identifiers.forEach((ID, index) => {
    const obj = {ID}

    for(const param of params){
      const urlAPI = baseUrl + param + ID

      fetch(urlAPI, {
        method: 'GET'
      }).then(res => {
        if(res.ok) return res.json()
        throw new Error('Network response error. Status Code:', res.status, res.statusText)
      }).then(data => {
        // Data structure of var store:
        // store = [ {id: freecodecamp, channels: {data}, streams: {data}, users: {data} } ]
        obj[matchCharUrl(param)] = data
      }).catch(err => {
        console.log('Fetch Error:', err)
      })
    }
    store.push(obj)
  })
  console.log(store) // OK
  console.log(store[0]) // OK
  console.log(store[0].ID) // OK
  console.log(store[0].users) // undefined
  console.log(store[0].channels) // undefined
  console.log(store[0].streams) // undefined
  // displayResults(store)
}
twitchAPI()
Redhelling
  • 1
  • 1
  • 2
  • 1
    becuase you are trying to eat the pizza before it is delivered to your house. fetch is asynchronous. Put a console.log() inside of the then() and see where the log appears compared to the others. Why does the log show the values when you expand it? Chrome lazy loads the object, it is not a snapshot in time. – epascarello Feb 20 '18 at 02:55
  • Indeed inside of the then() data is enabled. But I don't see how to store datas in a single variable. Fetch is in two loops, if I put logs (or function displayResults() ) into the then(), that will call for too much useless action, will not it? I don't really understand this notion of lazy load... – Redhelling Feb 20 '18 at 03:20
  • That is why you have promises to wait for it to come back. You are not waiting for the responses to come back, so it is not loaded. – epascarello Feb 20 '18 at 03:23
  • Ok, thanks for your answers, I understand better now why it does not work. Asynchronous is a concept still a little vague for me. I will look at the answers of the similar post. – Redhelling Feb 20 '18 at 03:32
  • Ok, I understand why store[n].users, store[n].channels, and store[n].streams send back undefined. Logs were call before then() is finished, isn't it? But why store[n] contains even so streams: {}, users{}, and channels{} ? Store[n] should be equal to Object {ID: "freecodecamp"}, isn't it ? – Redhelling Feb 20 '18 at 03:53
  • When you order delivery pizza. You make a call and go on your way until the doorbell rings. That is what happens here. you make a request for the data and than the code keeps running. Issue is you try to use the data before the doorbell rings. That is why you have callbacks and promises with Ajax calls so you know when the data is ready to be eaten. – epascarello Feb 20 '18 at 03:54
  • Why is Chrome showing the data when you expand it? Because Chrome lazy loads in the console. console.log is NOT a snapshot of the data in that moment in time. If you do `console.log(JSON.stringify(store))`, you will see the correct data at that moment in time. – epascarello Feb 20 '18 at 03:55
  • Ok ! that's it ! I understood the notion =) ! the example is very clear. Thanks for your patience ;) – Redhelling Feb 20 '18 at 04:07

0 Answers0