I am fetching data and I am passing props to other components. But in one of the child components I can’t using map() function. I am getting Cannot read properties of undefined (reading ‘map’). I think this is an asynchronous data problem. But I can’t solve it.
Here is my child component:
function WeeklyForecast({data}) {
console.log(data);
return (
<div className='WeeklyForecast'>
<div className="Prev-Btn">
<button><</button>
</div>
<div className="Forecast-List">
{data.map((forecast, index) => (
<div key={index}>
<p>{forecast[0]}</p>
</div>
))}
</div>
<div className="Next-Btn">
<button>></button>
</div>
</div>
)
}
There are my error and browser console results without map() function:
>Solution :
So the problem you are facing is you are trying to map over the data before it becomes available (as per your logs) what you want to do is make sure the data is available before blindly mapping over it… You can do such by checking that the data is available. You can learn more about conditional rendering here.
Just add a && (AND) clause to your statement, so that you can guarantee that data is not undefined and available.
This will give you the ability to wait for the data to load from your server.
So the statement becomes data && data.map(...)
So your code will look like the following.
function WeeklyForecast({data}) {
console.log(data);
return (
<div className='WeeklyForecast'>
<div className="Prev-Btn">
<button><</button>
</div>
<div className="Forecast-List">
{data && data.map((forecast, index) => (
<div key={index}>
<p>{forecast[0]}</p>
</div>
))}
</div>
<div className="Next-Btn">
<button>></button>
</div>
</div>
)
}

