Typescript: Array is empty after calling and passing it to function

Viewed 118

Hi I am building function to recursively "denest" a object of following interface:

export interface IUnit {
 code: string
 artifacts: IArtifact[]
 units: IUnit[]
}

The idea is that I have a separate array that I returns with every immersion and after each return the returned array is "pushed" to local array and so on...

the function is as following:

  const denestList = async (incomingUnit: IUnit): Promise<{ allUnits: IUnit[], allArtifacts: IArtifact[] }> => {
    var units = [incomingUnit];
    var artifacts = [...incomingUnit.artifacts];

    //Array is full
    console.log(unit.units)

    //Array is empty
    console.log(unit.units.length)
    console.log([...unit.units])
    console.log(Array.from(unit.units)?.length)

    for (unit of incomingUnit.units) {
        console.log(unit.code)
        //Recursion happens here.
        var result = await denestList(unit)

        units.push(...result.allUnits)
        artifacts.push(...result.allArtifacts)
    }

    return { allUnits: units, allArtifacts: artifacts }
}

The problem is that for (unit of incomingUnit.units) never happens. When I log unit.units it shows array full of IArtifact[], but when I run console.log(unit.units.length) it return 0.

Here is how to "denestList" function is called:

useEffect(() => {
    asyncStart(unit)
}, []);


const asyncStart = async (mainUnit: IUnit) => {
    var result = await denestList(mainUnit);

    setAllUnits(result.allUnits)
    setAllArtifacts(result.allArtifacts)
}

I would really appreciate any help. Thank you in advance

0 Answers
Related