0

I have a snippet of code which goes like this:

getLog (this is in a separate file)

export const getLog = async () => {
     return client.then(async () => {

        res1 = await method1()
        res2 = await method2(res1)
        // further parse data...
        return res4
    }
}

This function is async and it returns a promise which returns the result of various async calls.

getItem (React component)

const [items, setItems]=useState([])

 getItem = async () => {
    getLog().then((res: any) => {
        let finalArr: any = []
        res.map((val: any) => finalArr.push(val))
        console.log(res, finalArr)

        setItems(finalArr) 
    })
}

getItem()
  • res: prints Array(0) but whe I expand it in DevTools it shows an array of objects:

      0: {name: "x", property:"y", otherProperty:"z"}
      1: {name: "x", property:"y", otherProperty:"z"}
    
  • finalArr: prints Array(0) and when expanded it's indeed an empty array

It seems to me this is an array-like object (non-iterable).

How do I extract the data from this object?

What is interesting is that in React DevTools I can see the array is stored correctly in State but when I use {items.length} in templates it prints 0

(I am unable to produce a minimal example without rebuilding the async/await flow with mock data.)

dragonmnl
  • 14,578
  • 33
  • 84
  • 129
  • @CertainPerformance that's a good point. However, I don't need to use the return value of the promise (since I am basically using the getItem to set react state via hooks) – dragonmnl Oct 30 '20 at 15:03
  • 1
    My mistake, it looks like the problem is with `getLog`. Can you post the full code of `getLog`? The solution might be to use `Promise.all`, `getLog` sounds to be doing *something* other than just plain `await`ing on its top level – CertainPerformance Oct 30 '20 at 15:06
  • Are `res1`, `res2` and `res4` really undeclared (global) variables in `getLog`? Maybe something else modifies them. – Bergi Oct 30 '20 at 16:33

0 Answers0