Can not read property 'length' of undefined JAVASCRIPT

2

I'm just a fan of programming and as such I'm running into a certain problem. The code below gives me the following error:

Cannot read property 'length' of undefined
    at computeCourses

If I run the computeCourses () function from the chrome console if it works and I do not understand why, I appreciate your attention.

const urlJson = '../data/data.json'
let coursesRaw
let courses = []

const dataCohorts = () => {
  fetch(urlJson)
    .then(response => response.json())
    .then(response => {
      coursesRaw = response
    })
}

dataCohorts()

let computeCourses = () => {
  for (var i=0; i < coursesRaw.length; i++){
    courses.push(coursesRaw[i].id)
  }
}
computeCourses()
    
asked by Anthony Sotomayor 19.06.2018 в 00:42
source

2 answers

3

The problem is that fetch() is an asynchronous call. You must wait for the call to return so that the variable courseRaw is defined. You can do it like this:

const urlJson = '../data/data.json'
let coursesRaw
let courses = []

let computeCourses = () => {
  for (var i=0; i < coursesRaw.length; i++){
    courses.push(coursesRaw[i].id)
  }
}

const dataCohorts = () => {
  fetch(urlJson)
    .then(response => response.json())
    .then(response => {
      coursesRaw = response
      computeCourses()
    })
}

dataCohorts()
    
answered by 19.06.2018 в 00:50
1

what the error says: coursesRaw has no length because it is defined as undefined ,

dataCohorts may end up giving value to coursesRaw , but since it is a fetch that promises (at some point) to do so, computeCourses receives the disappointment of an unfulfilled promise. Or put another way, it rushes and does not wait.

    
answered by 19.06.2018 в 00:50