#TypeError: items is not defined

20 messages · Page 1 of 1 (latest)

normal knoll
#

I'm working on parsing json from a database, and eventually rendering ui elements from there. Currently, fetching data works, however I'm trying to cast the json returned from fetch into an array of interfaces called items (the array is named items). I am getting no intellisense errors, however my browser is throwing Uncaught (in promise) TypeError: items is undefined. I attached a screenshot from the console log.

Expected Behavior: The values from the database are passed into the array of interfaces.

function GetItemsFromDB()
{
    interface DB
    {
        itm1: string
        itm2: string
        itm3: string
        itm4: string
        itm5: string
        itm6: string
        itm7: string
        itm8: string
        itm9: string
        itm10: string
        itm11: string
    }
    let items: Array<DB>
    fetch('http://127.0.0.1:5000/')
        .then((response: any) => {
            if (!response.ok) {
                throw new Error(`HTTP error, status = ${response.status}`);
            }
            return response.json();
            })

        .then((database: any) => {
            for (const DB of database.values)
            {
                items.push({                        // Error is thrown here
                    itm1: DB["itm1"],
                    itm2: DB["itm2"],
                    itm3: DB["itm3"],
                    itm4: DB["itm4"],
                    itm5: DB["itm5"],
                    itm6: DB["itm6"],
                    itm7: DB["itm7"],
                    itm8: DB["itm8"],
                    itm9: DB["itm9"],
                    itm10: DB["itm10"],
                    itm11: DB["itm11"]
                })
            }

            console.log(items)
        })
}
export { GetItemsFromDB }
calm garnet
#

undefined != not defined
the issue here is that you haven't initialized items to an empty array

normal knoll
#

so i just need = {}?

calm garnet
#

that's an empty object, you need []

normal knoll
#

ah, gotcha

#

that fixed it

calm garnet
#

why the property transferral in the pushed object there though, why not just pass DB directly

normal knoll
#

are you talking about the for loop?

calm garnet
#

yes

#

for that matter, why not just use database.values directly?

#

you're mixing async with mutations there, that won't play well

normal knoll
#

alright

#

so its better to just use database.values, rather than converting it to an interface?

calm garnet
#

you aren't really converting anything

normal knoll
#

yeah

calm garnet
#

well, not in a useful way

#

it's any to begin with, so that makes any conversions kinda moot

normal knoll
#

okay

#

thanks

#

ill mark this as resolved