Home > Back-end >  how to access object in array of arrays of objects in react?
how to access object in array of arrays of objects in react?

Time:09-17

I did this:

const getData = async (array,s,number) => {
            const response = await axios.get(s);
            const theData = response.data
            array[number]=theData
        }

then this:

let array=[]
array.push(0)
getData(array, props.location.groupArray[i].link,0) //await axios.get(s) here returns an array of objects
console.log(array) //prints Array(1) 
console.log(array[0])//prints 0
console.log(array[0].length) //prints undefined

my question is why is array[0] here 0 and not an array of objects even though when I clck on Array(1) it shows:

"0: (99) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…},"

I need array to be an array of arrays of objects, in the original code I call getData more than once with 3rd parameter 0,1,2... after I push 0 to array, my problem here is I'll only know during runtime how many axios.get I'm gonna perform thats why I wanted an array of arrays of objects

CodePudding user response:

After you did:

array.push(0)

The content of your array became:

[0]

That is why accessing the first position of the array with array[0] returns the value 0, and printing array itself returns an Array object with length 1 (Array(1)).

On the other hand, since getData() is an asynchronous function, the content of array remains unchanged when you use console.log.

So you should for example use await for it if your code is inside an async function or use .then() and .catch after the function call with console.log inside it to handle both Promise resolve or reject cases.

Note: top-level await, aka calling await outside an async function, is not available yet in JavaScript, it is currently just a proposal for a future version

CodePudding user response:

I think using useState is good way to set array of objects to array in this problem and use useEffect for watching result

const [array,setArray] = useState([0])

const getData = async (array,s,number) => {
        const response = await axios.get(s);
        const theData = response.data
        setArray(prev=>prev.push(theData)
    }

also,

useEffect(()=>{
getData(array, props.location.groupArray[i].link,0)
},[]);

use other useEffect for watching result

useEffect(()=>{
console.log(array)
},[array]);

don't forget set off StrictMode in index.js

  • Related