import useSWR from "swr"; import { useState } from "react"; import { BiError } from "react-icons/bi"; import { WiCloudDown } from "react-icons/wi"; import { MdLocationDisabled, MdLocationSearching } from "react-icons/md"; import { useTranslation } from "next-i18next"; import Icon from "./icon"; function Widget({ options }) { const { t, i18n } = useTranslation(); const { data, error } = useSWR( `/api/widgets/openweathermap?${new URLSearchParams({ lang: i18n.language, ...options }).toString()}` ); if (error || data?.cod === 401 || data?.error) { return (
{t("widget.api_error")} -
); } if (!data) { return (
{t("weather.updating")} {t("weather.wait")}
); } const unit = options.units === "metric" ? "celsius" : "fahrenheit"; return (
data.sys.sunrise && data.dt < data.sys.sundown ? "day" : "night"} />
{options.label && `${options.label}, `} {t("common.number", { value: data.main.temp, style: "unit", unit })} {data.weather[0].description}
); } export default function OpenWeatherMap({ options }) { const { t } = useTranslation(); const [location, setLocation] = useState(false); const [requesting, setRequesting] = useState(false); if (!location && options.latitude && options.longitude) { setLocation({ latitude: options.latitude, longitude: options.longitude }); } const requestLocation = () => { setRequesting(true); if (typeof window !== "undefined") { navigator.geolocation.getCurrentPosition( (position) => { setLocation({ latitude: position.coords.latitude, longitude: position.coords.longitude }); setRequesting(false); }, () => { setRequesting(false); }, { enableHighAccuracy: true, maximumAge: 1000 * 60 * 60 * 3, timeout: 1000 * 30, } ); } }; // if (!requesting && !location) requestLocation(); if (!location) { return ( ); } return ; }