ENCOA-94: Fixes the bug, refactored useStats to be useFilterRecordsByUser in order to not duplicate code and also refactored records.tsx and training.tsx to use a component which abstracts the user Selection for both stats and training.
This commit is contained in:
50
src/hooks/useFilterRecordsByUser.tsx
Normal file
50
src/hooks/useFilterRecordsByUser.tsx
Normal file
@@ -0,0 +1,50 @@
|
||||
import axios from "axios";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
const endpoints: Record<string, string> = {
|
||||
stats: "/api/stats",
|
||||
training: "/api/training"
|
||||
};
|
||||
|
||||
export default function useFilterRecordsByUser<T extends any[]>(
|
||||
id?: string,
|
||||
shouldNotQuery?: boolean,
|
||||
recordType: 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 endpointURL = endpoints[recordType] || endpoints.stats;
|
||||
// CAUTION: This makes the assumption that the record enpoint has a /user/${id} endpoint
|
||||
const endpoint = !id ? endpointURL: `${endpointURL}/user/${id}`;
|
||||
|
||||
const getData = () => {
|
||||
if (shouldNotQuery) return;
|
||||
|
||||
setIsLoading(true);
|
||||
setIsError(false);
|
||||
|
||||
axios
|
||||
.get<T>(endpoint)
|
||||
.then((response) => {
|
||||
// CAUTION: This makes the assumption ElementType has a "user" field that contains the user id
|
||||
setData(response.data.filter((x: ElementType) => (id ? (x as any).user === id : true)) as T);
|
||||
})
|
||||
.catch(() => setIsError(true))
|
||||
.finally(() => setIsLoading(false));
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
getData();
|
||||
}, [id, shouldNotQuery, recordType, endpoint]);
|
||||
|
||||
return {
|
||||
data,
|
||||
reload: getData,
|
||||
isLoading,
|
||||
isError
|
||||
};
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
import {Stat, User} from "@/interfaces/user";
|
||||
import axios from "axios";
|
||||
import {useEffect, useState} from "react";
|
||||
|
||||
export default function useStats(id?: string, shouldNotQuery?: boolean) {
|
||||
const [stats, setStats] = useState<Stat[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isError, setIsError] = useState(false);
|
||||
|
||||
const getData = () => {
|
||||
if (shouldNotQuery) return;
|
||||
|
||||
setIsLoading(true);
|
||||
axios
|
||||
.get<Stat[]>(!id ? "/api/stats" : `/api/stats/user/${id}`)
|
||||
.then((response) => setStats(response.data.filter((x) => (id ? x.user === id : true))))
|
||||
.finally(() => setIsLoading(false));
|
||||
};
|
||||
|
||||
useEffect(getData, [id, shouldNotQuery]);
|
||||
|
||||
return {stats, reload: getData, isLoading, isError};
|
||||
}
|
||||
Reference in New Issue
Block a user