add useTableDataHook

This commit is contained in:
Pedro Losas 2024-11-11 22:57:33 +01:00
parent 0156587135
commit 4a0ad3bc0c
2 changed files with 50 additions and 21 deletions

View File

@ -0,0 +1,38 @@
import { useEffect, useState } from 'react';
type UseTableDataProps<T> = {
fetchData: () => Promise<T[]>;
};
type UseTableDataResult<T> = {
data: T[];
loading: boolean;
error: string | null;
};
export const useTableData = <T,>({
fetchData,
}: UseTableDataProps<T>): UseTableDataResult<T> => {
const [data, setData] = useState<T[]>([]);
const [loading, setLoading] = useState<boolean>(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
const loadData = async () => {
setLoading(true);
setError(null);
try {
const responseData = await fetchData();
setData(responseData);
} catch (error) {
console.error(error);
setError('Error fetching data');
}
setLoading(false);
};
loadData();
}, []);
return { data, loading, error };
};

View File

@ -1,13 +1,21 @@
import { Fragment, useEffect, useMemo, useState } from 'react'; import { Fragment, useMemo } from 'react';
import { getFaults } from '../../services/faults/get-faults'; import { getFaults } from '../../services/faults/get-faults';
import { Fault, FaultsResponse } from '../../models/fault.interface'; import { Fault, FaultsResponse } from '../../models/fault.interface';
import { MRT_ColumnDef, MaterialReactTable } from 'material-react-table'; import { MRT_ColumnDef, MaterialReactTable } from 'material-react-table';
import TableLoader from '../../components/table/TableLoader'; import TableLoader from '../../components/table/TableLoader';
import { useTableData } from '../../hooks/useTableData';
const Faults = () => { const Faults = () => {
const [faults, setFaults] = useState<Fault[]>([]); const {
const [loading, setLoading] = useState<boolean>(true); data: faults,
const [error, setError] = useState<string | null>(null); loading,
error,
} = useTableData<Fault>({
fetchData: async () => {
const result = (await getFaults()) as FaultsResponse;
return result.items as Fault[];
},
});
const columns = useMemo<MRT_ColumnDef<Partial<Fault>>[]>( const columns = useMemo<MRT_ColumnDef<Partial<Fault>>[]>(
() => [ () => [
@ -26,7 +34,6 @@ const Faults = () => {
header: 'Name', header: 'Name',
size: 150, size: 150,
}, },
{ {
accessorKey: 'contactoTelefono', accessorKey: 'contactoTelefono',
header: 'Telefono', header: 'Telefono',
@ -36,22 +43,6 @@ const Faults = () => {
[] []
); );
useEffect(() => {
const fetchData = async () => {
setLoading(true);
try {
const data = (await getFaults()) as FaultsResponse;
setFaults(data.items);
} catch (error) {
console.error(error);
setError('Error fetching data');
}
setLoading(false);
};
fetchData();
}, []);
return ( return (
<Fragment> <Fragment>
{loading && <TableLoader count={9} />} {loading && <TableLoader count={9} />}