36 lines
1.1 KiB
JavaScript
36 lines
1.1 KiB
JavaScript
// hooks/useWeather.js
|
|
|
|
import { useState, useEffect } from 'react';
|
|
import { locations } from '../config.js';
|
|
|
|
async function fetchWeather(lat, lon) {
|
|
const url = `https://api.open-meteo.com/v1/forecast?latitude=${lat}&longitude=${lon}¤t_weather=true&temperature_unit=celsius&timezone=Europe/Paris`;
|
|
const response = await fetch(url);
|
|
const data = await response.json();
|
|
return data.current_weather;
|
|
}
|
|
|
|
export function useWeather() {
|
|
const [weatherNancy, setWeatherNancy] = useState(null);
|
|
const [weatherParis, setWeatherParis] = useState(null);
|
|
|
|
async function updateWeatherData() {
|
|
try {
|
|
const [nancy, paris] = await Promise.all([
|
|
fetchWeather(locations.Nancy.latitude, locations.Nancy.longitude),
|
|
fetchWeather(locations.Paris.latitude, locations.Paris.longitude)
|
|
]);
|
|
setWeatherNancy(nancy);
|
|
setWeatherParis(paris);
|
|
} catch (_) { }
|
|
}
|
|
|
|
useEffect(() => {
|
|
updateWeatherData();
|
|
const interval = setInterval(updateWeatherData, 60000);
|
|
return () => clearInterval(interval);
|
|
}, []);
|
|
|
|
return { weatherNancy, weatherParis };
|
|
}
|