1
- import { useEffect , useState } from 'react' ;
1
+ import { useQuery } from '@tanstack/ react-query ' ;
2
2
3
3
import { APIError , errorCauses , gristFetchApi } from '@/api' ;
4
4
@@ -16,36 +16,36 @@ export interface Fields {
16
16
onDemand : boolean ;
17
17
}
18
18
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
+
19
39
export const useListGristTables = (
20
40
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
+ } ) ;
47
46
48
47
return {
49
48
tables,
49
+ isLoading,
50
50
} ;
51
51
} ;
0 commit comments