'How can I change background src dynamically in react based on api response?
I`m new to react, I tried to build a simple weather app, I made a full-screen video background and I want it to change the src dynamically based on the response I'm getting from the API,
here is my code:
import { useEffect, useState } from "react";
import { Background } from "./components/Background";
const api = {
key: "",
base: "https://api.openweathermap.org/data/2.5/",
};
function App() {
const [query, setQuery] = useState("");
const [weather, setWeather] = useState({});
const [backgroundVideo, setBackgroundVideo] = useState("");
const search = (e) => {
if (e.key === "Enter") {
fetch(`${api.base}weather?q=${query}&units=metric&APPID=${api.key}`)
.then((res) => res.json())
.then((result) => {
setWeather(result);
setBackgroundVideo(`${result.weather[0].description}`);//clear sky
setQuery("");
});
}
};
return (
<div className="bg">
{/**Video Background */}
{typeof weather.main !== "undefinde" &&
typeof weather.sys !== "undefined" ? (
<video autoPlay loop muted className="vid">
<source
src={`/videos/${backgroundVideo}.mp4`} // /videos/clear sky.mp4
type="video/mp4"
/>
</video>
) : (
""
)}
}
I'm getting all the data I want but it doesn't work, when I refresh the page there is no video, when I search for the first city it works(London -> scattered clouds), but if I searched for another city (Sanaa -> few clouds) it stays the same as before, although when I see the video source from dev tools it was updated!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
