reachy_mini_minder / frontend /src /hooks /useConsent.ts
Boopster's picture
initial commit
af9cde9
"use client";
import { useState, useEffect, useCallback } from "react";
// API server runs on port 7860
const API_BASE = "http://localhost:7860";
interface UseConsentReturn {
hasConsented: boolean;
consentDate: string | null;
isLoading: boolean;
giveConsent: () => Promise<void>;
withdrawConsent: () => Promise<void>;
}
export function useConsent(): UseConsentReturn {
const [hasConsented, setHasConsented] = useState(false);
const [consentDate, setConsentDate] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(true);
const fetchConsentState = useCallback(async () => {
try {
const response = await fetch(`${API_BASE}/api/consent`);
if (response.ok) {
const data = await response.json();
setHasConsented(data.consented);
setConsentDate(data.consent_date);
}
} catch (error) {
console.error("Failed to fetch consent state:", error);
} finally {
setIsLoading(false);
}
}, []);
const giveConsent = useCallback(async () => {
try {
const response = await fetch(`${API_BASE}/api/consent`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ consented: true }),
});
if (response.ok) {
const data = await response.json();
setHasConsented(data.consented);
setConsentDate(data.consent_date);
}
} catch (error) {
console.error("Failed to give consent:", error);
}
}, []);
const withdrawConsent = useCallback(async () => {
try {
const response = await fetch(`${API_BASE}/api/consent`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ consented: false }),
});
if (response.ok) {
setHasConsented(false);
setConsentDate(null);
}
} catch (error) {
console.error("Failed to withdraw consent:", error);
}
}, []);
useEffect(() => {
fetchConsentState();
}, [fetchConsentState]);
return {
hasConsented,
consentDate,
isLoading,
giveConsent,
withdrawConsent,
};
}