1

I successfully export a function that returns an array and calls that function from a another JavaScript file. When I try to take the length of the array it throws this error

Cannot read property 'length' of undefined

I verified that array is not empty by using console.log(ModelItems).

The error is not showing up when I use a hardcoded array like this below

var ModelItems = [{name: "bla"},{name: "blaBla"},]

_getListItems() function calls _constructListArrayModel function in app.js with giving the said array as a parameter. _constructListArrayModel function tries to get the array's length but throws the said error.

I just want to get the length of the array in order to run the for loop.

//ModelItems.js that exports the array

module.exports = {
  getModelArray: function(uid) {
    firebase.database().ref('ArArray').child(uid).once('value').then(function(snapshot){
      const exists = (snapshot.val() !== null)
      data = snapshot.val()
      var ModelItems = []
      for(var obj in data){
        ModelItems.push({
          name: data.name,
          selected: false,
          loading: LoadingConstants.NONE,
          icon_img: data.icon_img,
          obj: data.obj,
          materials: null,
          animation:{name:"01", delay:0, loop:true, run:true},
          scale: [0.2, 0.2, 0.2],
          position : [0, 5*0.05, 10],
          type : "OBJ",
          physics: undefined,
          ref_pointer: undefined,
          shadow_width: 60.5,
          shadow_height: 60.5,
          spotlight_position_y: 100,
          lighting_mode: "IBL",
      })
      }
      console.log(ModelItems)
      return ModelItems
    })
  }
}
// app.js that calls the function

_getListItems() {
  if(this.props.listMode == UIConstants.LIST_MODE_MODEL){
    return this._constructListArrayModel(ModelData.getModelArray(firebase.auth().currentUser.uid), this.props.modelItems);
  }
  else
  {
   return null
  }
} 

// 

_constructListArrayModel(sourceArray, items) {
    var listArrayModel = [];
    for(var i =0; i<sourceArray.length; i++) {
        listArrayModel.push({icon_img:sourceArray[i].icon_img, loading:this._getLoadingforModelIndex(i, items)})
    }
  return listArrayModel;
}


  • 1
    I was able to find problem. I was trying to return a array inside the firebase function. But does not have access to do so. So I had to make reference to the array inside the firebase function and then return it. – Hiran Tharinda Aug 12 '19 at 07:35

0 Answers0