Files
encoach_frontend/src/hooks/useUsers.tsx
2024-09-07 17:34:41 +01:00

42 lines
1.5 KiB
TypeScript

import {Type, User} from "@/interfaces/user";
import Axios from "axios";
import {useEffect, useState} from "react";
import {setupCache} from "axios-cache-interceptor";
const instance = Axios.create();
const axios = setupCache(instance);
export const userHashStudent = {type: "student"} as {type: Type};
export const userHashTeacher = {type: "teacher"} as {type: Type};
export const userHashCorporate = {type: "corporate"} as {type: Type};
export default function useUsers(props?: {type?: string; page?: number; size?: number; orderBy?: string; direction?: "asc" | "desc"}) {
const [users, setUsers] = useState<User[]>([]);
const [total, setTotal] = useState(0);
const [isLoading, setIsLoading] = useState(false);
const [isError, setIsError] = useState(false);
const getData = () => {
const params = new URLSearchParams();
if (!!props)
Object.keys(props).forEach((key) => {
if (props[key as keyof typeof props] !== undefined) params.append(key, props[key as keyof typeof props]!.toString());
});
console.log(params.toString());
setIsLoading(true);
axios
.get<{users: User[]; total: number}>(`/api/users/list?${params.toString()}`, {headers: {page: "register"}})
.then((response) => {
setUsers(response.data.users);
setTotal(response.data.total);
})
.finally(() => setIsLoading(false));
};
useEffect(getData, [props?.page, props?.size, props?.type, props?.orderBy, props?.direction]);
return {users, total, isLoading, isError, reload: getData};
}