So I'm trying to create a simple enough weather app using React. I've decided that there's going to be one search box where the user types in the city name (using an onchange on the input)and when submitted, it will:
1: Change the background image to show a random image of that city from the UnSplash API. (I coded this first and it works fine.) 2. It will show relevant weather details below such as temp, wind speed etc.
function App() {
const [city, setCity] = useState("");
const fetchCityImage = (e) => {
e.preventDefault();
axios
.get(
`https://api.unsplash.com/photos/random?query=${city}&client_id={API_KEY}`
)
.then((response) => {
console.log(response.data);
setCity(response.data.urls.regular);
});
};
const fetchCityWeather = (e) => {
e.preventDefault();
axios
.get(
`https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=${OTHER_API_KEY}`
)
.then((response) => {
console.log(response.data);
});
};
return (
<div className="App">
{/* HEADER */}
<div className="bg-black w-full h-[600px]">
<img
src={city}
alt="city image"
className="w-full h-[600px] object-cover"
/>
{/* Search and Info */}
<div className="absolute w-full h-[600px] top-[0%] flex flex-col justify-center bg-gradient-to-t from-black">
<div className="flex justify-center py-4">
<h1 className="font-bold">Weather App</h1>
</div>
<div className="flex justify-center">
<form
onSubmit={fetchCityWeather}
className="flex justify-between border border-white rounded-xl max-w-[300px] p-4"
>
<input
onChange={(e) => setCity(e.target.value)}
className="bg-transparent focus:outline-none placeholder:text-white"
type="text"
placeholder="Search a City..."
/>
<button onClick={fetchCityWeather}>
<BsSearch size={20} />
</button>
</form>
</div>
</div>
</div>
{/* DATA */}
</div>
);
}
export default App;
This is where I run into a problem. I can log my weather data to the console but how do I go about linking that API call to the same input field. Or the same state even to use that data on the rest of the page? I've been switching out the onClick and onSubmit to get the two different results I want but need them together.
I hope I explained that well enough. Thanks guys.