The condition is calling before fetch, so I can’t render the image on the page.
I need to set an icon based on the API data.
-
Call an API for weather data, then set it to
weatherData
state -
Set the weather Icon/image based on the data
Here Icon/image is external, so I use a switch statement to define the icon
<code>import rain from "../src/Images/rain.jpg";
import fog from "../src/Images/fog.jpg";
import snow from "../src/Images/snow.jpg";
import wind from "../src/Images/wind.jpg";
import cloudy from "../src/Images/cloudy.png";
import sn from "../src/Images/sn.jpg";
let newBG;
useEffect(() => {
fetchData // <==fetching data
}, []);
useEffect(() => {
setbgTheme(newBg); // <== setting Bg
}, [newBG]);
switch (weatherData? weatherData.currentConditions.icon: "sn") {
case "rain":
newBg = rain;
break;
case "fog":
newBg = fog;
break;
case "cloudy":
newBg = cloudy;
break;
case "snow":
newBg = snow;
break;
case "wind":
newBg = wind;
break;
case "sn":
newBg = sn;
}
</code>
<code>import rain from "../src/Images/rain.jpg";
import fog from "../src/Images/fog.jpg";
import snow from "../src/Images/snow.jpg";
import wind from "../src/Images/wind.jpg";
import cloudy from "../src/Images/cloudy.png";
import sn from "../src/Images/sn.jpg";
let newBG;
useEffect(() => {
fetchData // <==fetching data
}, []);
useEffect(() => {
setbgTheme(newBg); // <== setting Bg
}, [newBG]);
switch (weatherData? weatherData.currentConditions.icon: "sn") {
case "rain":
newBg = rain;
break;
case "fog":
newBg = fog;
break;
case "cloudy":
newBg = cloudy;
break;
case "snow":
newBg = snow;
break;
case "wind":
newBg = wind;
break;
case "sn":
newBg = sn;
}
</code>
import rain from "../src/Images/rain.jpg";
import fog from "../src/Images/fog.jpg";
import snow from "../src/Images/snow.jpg";
import wind from "../src/Images/wind.jpg";
import cloudy from "../src/Images/cloudy.png";
import sn from "../src/Images/sn.jpg";
let newBG;
useEffect(() => {
fetchData // <==fetching data
}, []);
useEffect(() => {
setbgTheme(newBg); // <== setting Bg
}, [newBG]);
switch (weatherData? weatherData.currentConditions.icon: "sn") {
case "rain":
newBg = rain;
break;
case "fog":
newBg = fog;
break;
case "cloudy":
newBg = cloudy;
break;
case "snow":
newBg = snow;
break;
case "wind":
newBg = wind;
break;
case "sn":
newBg = sn;
}
Here switch statement is called before the fetch, so I use a setTimeout function for the switch statement.
Still, it is not rendering.