Hey I am experiencing a strange bug when I console.log(typeof(variable)
compared to console.log(variable)
.
In the console the variable is clearly an array of objects, but when I console.log
the typeof
it says it's an object
.
I am fetching from an API and then trying to render the data into react.
I think I cannot map
through the data as it thinks it's an object.
Any help would be really appreciated, thank you!
Below is my RenderDrink component
import React from 'react'
function RenderDrinks(props) {
console.log(typeof(props.data))
console.log(props.data)
return (
props.data && props.data.map(drink => {
<>
<h2>{drink.strDrink}</h2>
<p>{drink.strGlass}</p>
<p>{drink.strImageSource}</p>
<p>{drink.strInstructions}</p>
{/* <p>{drink.str}</p>
<p>{drink.str}</p> */}
</>
})
)
}
export default RenderDrinks
Below is my ApiFetch component
import React, {useState, useEffect} from 'react'
import axios from 'axios'
import RenderDrinks from '../RenderDrinks';
const FetchApi = () => {
const [data, setData] = useState([]);
const fetchDrinks = async () => {
await axios.get('https://www.thecocktaildb.com/api/json/v2/9973533/popular.php')
.then((res) => {
const allDrinks = res.data.drinks
setData(allDrinks)
console.log(typeof(data))
})
.catch(error => console.error(`Error: ${error}`))
}
useEffect(() => {
fetchDrinks()
}, [])
return (
<>
<RenderDrinks data={data} />
</>
)
}
export default FetchApi
CodePudding user response:
That's because array
is of type object
If you want to test a variable of array, you can use:
if (data.constructor === Array)
console.log('it's an array');
You can also use isArray() to check if it's an array like this:
if(typeof data === 'object' &&
Array.isArray(data)) {
//Its an array
}