From 4a0ad3bc0c1044088e4fb9b1cf6fceab713cb1b0 Mon Sep 17 00:00:00 2001 From: Pedro Losas Date: Mon, 11 Nov 2024 22:57:33 +0100 Subject: [PATCH] add useTableDataHook --- src/hooks/useTableData.tsx | 38 +++++++++++++++++++++++++++++++++++++ src/pages/faults/Faults.tsx | 33 ++++++++++++-------------------- 2 files changed, 50 insertions(+), 21 deletions(-) create mode 100644 src/hooks/useTableData.tsx diff --git a/src/hooks/useTableData.tsx b/src/hooks/useTableData.tsx new file mode 100644 index 0000000..5ea89de --- /dev/null +++ b/src/hooks/useTableData.tsx @@ -0,0 +1,38 @@ +import { useEffect, useState } from 'react'; + +type UseTableDataProps = { + fetchData: () => Promise; +}; + +type UseTableDataResult = { + data: T[]; + loading: boolean; + error: string | null; +}; + +export const useTableData = ({ + fetchData, +}: UseTableDataProps): UseTableDataResult => { + const [data, setData] = useState([]); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(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 }; +}; diff --git a/src/pages/faults/Faults.tsx b/src/pages/faults/Faults.tsx index 1267297..16e3364 100644 --- a/src/pages/faults/Faults.tsx +++ b/src/pages/faults/Faults.tsx @@ -1,13 +1,21 @@ -import { Fragment, useEffect, useMemo, useState } from 'react'; +import { Fragment, useMemo } from 'react'; import { getFaults } from '../../services/faults/get-faults'; import { Fault, FaultsResponse } from '../../models/fault.interface'; import { MRT_ColumnDef, MaterialReactTable } from 'material-react-table'; import TableLoader from '../../components/table/TableLoader'; +import { useTableData } from '../../hooks/useTableData'; const Faults = () => { - const [faults, setFaults] = useState([]); - const [loading, setLoading] = useState(true); - const [error, setError] = useState(null); + const { + data: faults, + loading, + error, + } = useTableData({ + fetchData: async () => { + const result = (await getFaults()) as FaultsResponse; + return result.items as Fault[]; + }, + }); const columns = useMemo>[]>( () => [ @@ -26,7 +34,6 @@ const Faults = () => { header: 'Name', size: 150, }, - { accessorKey: 'contactoTelefono', 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 ( {loading && }