Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | 1x 1x 1x 1x 10x 10x 10x 10x 10x 5x 5x 1x 1x 4x 4x 4x 4x 3x 2x 2x 2x 4x 4x 4x 10x | import { useEffect, useState } from "react";
import { useAuth } from "./useAuth";
import { UserData } from "../api/types/user";
import { getUserData } from "../api/user";
/**
* Custom hook to fetch user data based on user ID or authenticated user.
* @param {string} userId - Optional user ID to fetch specific user data.
* @returns {Object} - Contains userData, loading state, and error message.
*/
export const useUserData = (userId?: string) => {
const { user } = useAuth();
const [userData, setUserData] = useState<UserData | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
const idToFetch = userId ?? user?.id;
if (!idToFetch) {
setLoading(false);
return;
}
const fetchUserData = async () => {
try {
setError(null);
const response = await getUserData(idToFetch);
if (response.error) throw new Error(response.error);
Iif (!response.data) {
setUserData(null);
setLoading(false);
return;
}
setUserData(response.data);
} catch (err) {
setError(err instanceof Error ? err.message : "Unknown error");
} finally {
setLoading(false);
}
};
const debounceTimer = setTimeout(fetchUserData, 300);
return () => clearTimeout(debounceTimer);
}, [userId, user]);
return { userData, loading, error };
};
|