Skip to content

Commit fc4ad24

Browse files
ClemsazertSimonClo
authored andcommitted
♻️ useQuery in listGristTable
1 parent b1cab34 commit fc4ad24

File tree

1 file changed

+27
-27
lines changed

1 file changed

+27
-27
lines changed
Lines changed: 27 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { useEffect, useState } from 'react';
1+
import { useQuery } from '@tanstack/react-query';
22

33
import { APIError, errorCauses, gristFetchApi } from '@/api';
44

@@ -16,36 +16,36 @@ export interface Fields {
1616
onDemand: boolean;
1717
}
1818

19+
const listTables = async (documentId: number) => {
20+
const url = `docs/${documentId}/tables`;
21+
const response = await gristFetchApi(url);
22+
23+
if (!response.ok) {
24+
throw new APIError(
25+
'Failed to fetch Grist tables',
26+
await errorCauses(response),
27+
);
28+
}
29+
30+
const tableDescription = (await response.json()) as TableDescription;
31+
return tableDescription.tables;
32+
};
33+
34+
type UseListGristTablesReturnType = {
35+
tables: Table[] | undefined;
36+
isLoading: boolean;
37+
};
38+
1939
export const useListGristTables = (
2040
documentId: number,
21-
): { tables: Table[] | undefined } => {
22-
const [tables, setTables] = useState<Table[]>();
23-
24-
useEffect(() => {
25-
const fetchTables = async () => {
26-
const url = `docs/${documentId}/tables`;
27-
const response = await gristFetchApi(url);
28-
if (!response.ok) {
29-
throw new APIError(
30-
'Failed to fetch Grist tables',
31-
await errorCauses(response),
32-
);
33-
}
34-
return (await response.json()) as Promise<TableDescription>;
35-
};
36-
37-
fetchTables()
38-
.then((response) => {
39-
if (response) {
40-
setTables(response.tables);
41-
}
42-
})
43-
.catch((error) => {
44-
console.error('Error fetching Grist documents:', error);
45-
});
46-
}, [documentId]);
41+
): UseListGristTablesReturnType => {
42+
const { data: tables, isLoading } = useQuery<Table[]>({
43+
queryKey: ['listTables', documentId],
44+
queryFn: () => listTables(documentId),
45+
});
4746

4847
return {
4948
tables,
49+
isLoading,
5050
};
5151
};

0 commit comments

Comments
 (0)