init projet
This commit is contained in:
@@ -0,0 +1,33 @@
|
||||
/* Hook générique pour les appels API : retourne { data, loading, error, refetch } */
|
||||
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
|
||||
/**
|
||||
* @param {Function} fetchFn - Fonction async à appeler (depuis api.js)
|
||||
* @param {Array} deps - Dépendances qui déclenchent un re-fetch (optionnel)
|
||||
*/
|
||||
export function useApi(fetchFn, deps = []) {
|
||||
const [data, setData] = useState(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState(null);
|
||||
|
||||
const fetch = useCallback(async () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const result = await fetchFn();
|
||||
setData(result);
|
||||
} catch (err) {
|
||||
setError(err.message || 'Une erreur est survenue.');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, deps);
|
||||
|
||||
useEffect(() => {
|
||||
fetch();
|
||||
}, [fetch]);
|
||||
|
||||
return { data, loading, error, refetch: fetch };
|
||||
}
|
||||
Reference in New Issue
Block a user