hooks/useNetworkStatus.ts

hook·mobile·0.9 KB · 38 lignes· Voir l'itinéraire
Annotation non disponible

Lance npm run annotate (nécessite ANTHROPIC_API_KEY dans .env.local) pour générer une annotation française par Claude Haiku 4.5.

1 export

useNetworkStatus

Code source· typescript

import { useEffect, useState } from 'react';
import { API_URL } from '@/lib/constants';

const PING_URL = `${API_URL}/mobile/health`;
const PING_INTERVAL_MS = 30000;
const PING_TIMEOUT_MS = 3000;

export function useNetworkStatus() {
  const [isOnline, setIsOnline] = useState(true);

  useEffect(() => {
    let mounted = true;

    const check = async () => {
      const controller = new AbortController();
      const timer = setTimeout(() => controller.abort(), PING_TIMEOUT_MS);
      try {
        const r = await fetch(PING_URL, { method: 'GET', signal: controller.signal });
        if (mounted) setIsOnline(r.ok);
      } catch {
        if (mounted) setIsOnline(false);
      } finally {
        clearTimeout(timer);
      }
    };

    check();
    const interval = setInterval(check, PING_INTERVAL_MS);

    return () => {
      mounted = false;
      clearInterval(interval);
    };
  }, []);

  return isOnline;
}