33 lines
884 B
TypeScript
33 lines
884 B
TypeScript
import { useEffect, useState } from 'react';
|
|
import { WeatherData } from '~/types';
|
|
|
|
function fetchWeather(): Promise<WeatherData> {
|
|
const lat = import.meta.env.VITE_OPEN_WEATHER_LAT;
|
|
const lon = import.meta.env.VITE_OPEN_WEATHER_LON;
|
|
const appId = import.meta.env.VITE_OPEN_WEATHER_KEY;
|
|
|
|
return fetch(
|
|
`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${appId}&units=metric`
|
|
)
|
|
.then((res) => res.json())
|
|
.then((data) => ({
|
|
...data.weather[0],
|
|
...data.main,
|
|
visibility: data.visibility,
|
|
wind_speed: data.wind.speed,
|
|
wind_deg: data.wind.deg,
|
|
sunrise: data.sys.sunrise,
|
|
sunset: data.sys.sunset,
|
|
}));
|
|
}
|
|
|
|
export function useWeather() {
|
|
const [weather, setWeather] = useState<WeatherData | null>(null);
|
|
|
|
useEffect(() => {
|
|
fetchWeather().then(setWeather);
|
|
}, []);
|
|
|
|
return weather;
|
|
}
|