Im trying to render out the items of an array to the screen and display the items. So I did the .map function. However, when I do the map function, it says that cars.map is not a function. I console logged the items in the car array and it was indeed populated. Is there anything that I am doing wrong here? Any advice helps! Thanks!
const [cars, setCars] = useState([]);
And where the cars array is being set:
useEffect(async () => {
const result = await initCarsInfo();
setCars(result);
}, []);
console.log(cars);
Here is the console log of cars
{cars: Array(2)}cars: Array(2)0: {name: 'Lexus ES', year: 1995, totalMiles: 200000, …}1: {name: 'Kia Sonota', year: 2005, totalMiles: 250000, …}length: 2[[Prototype]]: Array(0)[[Prototype]]: Object
And where I am mapping it:
const getAssetMenuItems = () => {
{cars && cars.map(carObj => {
return (
<MenuItem value="car1">
<span style={{ marginLeft: '10px' }}>
<Typography className={classes.carsName}>{carObj.name}</Typography>
<Typography>{carObj.year}</Typography>
</span>
</MenuItem>
)
})}
};
CodePudding user response:
I console logged the items in the car array and it was indeed populated - This is sort of true, but not how you're expecting.
It appears that cars
from your initCarsInfo
is returning an object that contains the cars
, not returning the array directly.
Notice that your console log shows that the value of cars
is an object: {cars: Array(2)}
.
You'll need to access that property from the result when setting the state:
useEffect(async () => {
const result = await initCarsInfo();
setCars(result.cars);
}, []);
CodePudding user response:
You need to call like this:
useEffect(async () => {
const result = await initCarsInfo();
setCars(result.cars);
}, []);