0

I've coded this class that upon being instantiated retrieves data from the database and for each record found instatiates an Issue object which is immediately stored into an array.

import { Issue } from "./Issue.js";

class App {

    constructor() {
        
        this.issues = [];

        fetch("/issues")
           
            .then(response => {

                if(response.ok) return response.json();
            })
            
            .then(issues => {

                issues.forEach(model => {
                    
                    let issue = new Issue(model);
                    this.issues.push(issue);
                })
            });

        console.log(this.issues);
    }
}
    
let app = new App();

This code prints out an array containing as many objects as there are records in the database.

enter image description here

However, what's weird is that if I try to print an element of this array as this:

console.log(this.issues[0]);

The output that I get is just "undefined". What's happening here?

Gian
  • 327
  • 2
  • 8
  • 1
    The array is empty when you log it. Move the log inside the `then` callback. – Bergi Sep 20 '20 at 13:06
  • 2
    And in general, [don't start asynchronous tasks inside constructors](https://stackoverflow.com/q/24398699/1048572). – Bergi Sep 20 '20 at 13:06

0 Answers0