import axios from "axios"; import { useCallback, useEffect, useState } from "react"; export default function useStats( id?: string, shouldNotQuery: boolean = !id, queryType: string = "stats" ) { type ElementType = T extends (infer U)[] ? U : never; const [data, setData] = useState({} as unknown as T); const [isLoading, setIsLoading] = useState(false); const [isError, setIsError] = useState(false); const getData = useCallback(() => { if (shouldNotQuery) return; setIsLoading(true); setIsError(false); let endpoint = `/api/stats/user/${id}`; if (queryType) endpoint += `?query=${queryType}`; axios .get(endpoint) .then((response) => { console.log(response.data); setData(response.data); }) .catch(() => setIsError(true)) .finally(() => setIsLoading(false)); }, [id, shouldNotQuery, queryType]); useEffect(() => { getData(); }, [getData]); return { data, reload: getData, isLoading, isError, }; }