feat: implement WeatherForm component and integrate weather fetching functionality.
Also added a weather data card where the design is displayed
This commit is contained in:
70
frontend/src/components/WeatherForm.tsx
Normal file
70
frontend/src/components/WeatherForm.tsx
Normal file
@@ -0,0 +1,70 @@
|
||||
import React from "react";
|
||||
import { useState } from "react";
|
||||
import { fetchWeather } from "../utils/apiFunc";
|
||||
import Cookies from "js-cookie";
|
||||
import { toast } from "react-toastify";
|
||||
import WeatherData from "./WeatherData";
|
||||
import { useEffect } from "react";
|
||||
|
||||
const WeatherCard: React.FC = () => {
|
||||
const [city, setCity] = useState("");
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [weatherData, setWeatherData] = useState(false);
|
||||
console.log(loading); // only for better reading because a syntax error would appear
|
||||
const getAPIKey = () => Cookies.get("apiKey") || "";
|
||||
|
||||
const handleCityChange = (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
setCity(event.target.value);
|
||||
};
|
||||
|
||||
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
setLoading(true);
|
||||
toast
|
||||
.promise(fetchWeather(city, getAPIKey(), "metric"), {
|
||||
pending: "Fetching weather data...",
|
||||
success: "Weather data loaded successfully!",
|
||||
error: "Error loading weather data! (Check console for details)",
|
||||
})
|
||||
.then(() => {
|
||||
if (localStorage.getItem("weather")) {
|
||||
setWeatherData(true);
|
||||
} else {
|
||||
setWeatherData(false);
|
||||
}
|
||||
setLoading(false);
|
||||
});
|
||||
};
|
||||
|
||||
// Check if weather data is already in localStorage - when entering the page via URL/reload
|
||||
useEffect(() => {
|
||||
if (localStorage.getItem("weather")) {
|
||||
setWeatherData(true);
|
||||
} else {
|
||||
setWeatherData(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<>
|
||||
<h2>Weather Card</h2>
|
||||
<p>Current Weather will be displayed here</p>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<label htmlFor="city">Enter City:</label>
|
||||
<input
|
||||
type="text"
|
||||
id="city"
|
||||
name="city"
|
||||
onChange={handleCityChange}
|
||||
value={city}
|
||||
placeholder="City Name"
|
||||
required
|
||||
/>
|
||||
<button type="submit">Get Weather</button>
|
||||
</form>
|
||||
{weatherData && <WeatherData />}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default WeatherCard;
|
Reference in New Issue
Block a user