TypeError: undefined is not an object (evaluating 'parkingLotData[i]')

16 Views Asked by At

I'm using fetch() to read some parking lot data I'm storing in a JSON file, and initializeInterface() to put the interface together on load. I keep getting the error listed above.

Here's my code:

In the page, outside the document ready handler:

        function readJSONdata(fp){
            return fetch(fp)
            .then(response => {
                if(!response.ok){
                    throw new Error('Network response was not ok');
                }else{
                    let jsonData = response.json(); // store the parking lot data
                    return jsonData;
                }
            })
            .catch(error => {
                console.error('Error reading file:', error);
                throw error; // rethrow the error to propagate it to the caller
            });
        }

Inside the document ready handler:

            readJSONdata('data.json')
            .then((result) => {
                parkingLotData = result;
                return parkingLotData;
            })
            .catch((error) => {
                console.error("An error occurred:", error);
            });

            function initializeInterface(){
                const array = [1, 2, 3, 4]
                for(const i of array){
                    const $curSpaceJSON = parkingLotData[i];
                    console.log($curSpaceJSON.number, $curSpaceJSON.occupied, $curSpaceJSON.occupant)
                }
            }

initializeInterface();

All the .then() statements are returning something. Console.log()-ing jsonData in the first function shows me an Object, so as far as I can tell everything should be ok. Can anyone tell me what's wrong here?

0

There are 0 best solutions below