Refactor components to remove Layout wrapper and pass it in the App component , implemented a skeleton feedback while loading page and improved API calls related to Dashboard/User Profile
43 lines
1.0 KiB
TypeScript
43 lines
1.0 KiB
TypeScript
import axios from "axios";
|
|
import { useCallback, useEffect, useState } from "react";
|
|
|
|
export default function useStats<T extends any>(
|
|
id?: string,
|
|
shouldNotQuery: boolean = !id,
|
|
queryType: string = "stats"
|
|
) {
|
|
type ElementType = T extends (infer U)[] ? U : never;
|
|
|
|
const [data, setData] = useState<T>({} 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<T>(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,
|
|
};
|
|
}
|