/
masterOK
/
FEF
Обзор
Документация
Войти
/
masterOK
/
FEF
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
main
useGeolocation.ts
83 строки
2 KB
masterOK
upload files
10 ноя 2025, 19:52
10 ноя 2025, 19:52
2cb4a49
Код
Авторство
О чём код?
import { useState, useEffect } from "react"; import { useToast } from "@/hooks/use-toast"; import { apiRequest } from "@/lib/queryClient"; export interface Coordinates { latitude: number; longitude: number; } export function useGeolocation() { const [location, setLocation] = useState<Coordinates | null>(null); const [error, setError] = useState<string | null>(null); const [loading, setLoading] = useState(true); const { toast } = useToast(); const requestGeolocation = () => { if (!navigator.geolocation) { setError("Геолокация не поддерживается вашим браузером"); setLoading(false); return; } setLoading(true); navigator.geolocation.getCurrentPosition( (position) => { const coords = { latitude: position.coords.latitude, longitude: position.coords.longitude, }; setLocation(coords); setError(null); setLoading(false); apiRequest({ url: "/api/user/location", method: "PATCH", data: coords, }).catch((err) => { console.error("Failed to save location:", err); }); }, (err) => { let message = "Не удалось определить местоположение"; switch (err.code) { case err.PERMISSION_DENIED: message = "Вы отклонили запрос на определение местоположения"; break; case err.POSITION_UNAVAILABLE: message = "Информация о местоположении недоступна"; break; case err.TIMEOUT: message = "Превышено время ожидания запроса"; break; } setError(message); setLoading(false); toast({ title: "Ошибка геолокации", description: message, variant: "destructive", }); } ); }; useEffect(() => { const authToken = localStorage.getItem("authToken"); if (!authToken) { setLoading(false); return; } const hasAsked = localStorage.getItem("geolocation-asked"); if (!hasAsked) { requestGeolocation(); localStorage.setItem("geolocation-asked", "true"); } else { setLoading(false); } }, []); return { location, error, loading, requestGeolocation }; }