I am trying to make an API call and conditionally render data to the page. If it meets a certain criteria (date in this case), I want to display it, otherwise I don't want it to show up on the page. However, when I type in null I still get 4 items logging as "null" in my console (I only want the 'display to page' item to show up). I have followed this approach in previous projects and it has worked...anyone know what might be happening here? Any insights would be appreciated, thanks!
useEffect(() => {
axios({
method: "get",
url: `http://dataservice.accuweather.com/forecasts/v1/daily/5day/${userInput}`,
params: {
apikey: "<API_key>",
},
})
.then((response) => {
setWeatherData(
response.data.DailyForecasts.map((item) => {
console.log(
item.Date === "2022-05-31T07:00:00-04:00"
? "display to page"
: null
);
})
);
})
.catch((error) => {
console.log(error);
});
}, [userInput]);
When mapping over it in the jsx, I did this:
<section className="wrapper weatherContainer">
{weatherData.map((data) => {
console.log(data);
return (
<div className="topContainer">
{/* if date matches today's date, display on top container, otherwise don't display anything */}
{
data.Date === "2022-05-31T07:00:00-04:00" ? (
<div className="topContainer">
<h1>Today</h1>
<p>
<img
src={require(`../../assets/${data.Day.Icon}.png`)}
alt={data.Day.IconPhrase}
/>
{toCelcius(data.Temperature.Maximum.Value).toFixed(0)}°
</p>
<p>{data.Day.IconPhrase}</p>
</div>
) : null
}
</div>
);
})}
</section>
Empty <div>s show up because the first map function within <section> tags return a <div className="topContainer"> even if the item does not match. Returning the item only if it is matched does the trick.
<section className="wrapper weatherContainer">
{weatherData.map((data) => {
console.log(data);
return (
data.Date === "2022-05-31T07:00:00-04:00" ? (
<div className="topContainer">
<h1>Today</h1>
... rest of the elements
</div>
) : null
);
})}
</section>
You are not logging properly. Look, in your ternary operator, you say if true - log "display to page", else log null. To log only elements which are
item.Date === "2022-05-31T07:00:00-04:00"
You need to do this way
if(item.Date === "2022-05-31T07:00:00-04:00") console.log(item)