File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ import { useState , useEffect , useCallback } from "react" ;
2+ import * as accountService from "../services/account-service" ;
3+ import type { Account } from "../types/Account" ;
4+
5+ interface UseAccountsState {
6+ data : Account [ ] ;
7+ loading : boolean ;
8+ error : boolean ;
9+ }
10+
11+ export const useAccounts = ( ) => {
12+ const [ state , setState ] = useState < UseAccountsState > ( {
13+ data : [ ] ,
14+ loading : false ,
15+ error : false ,
16+ } ) ;
17+
18+ const fetch = useCallback ( ( ) => {
19+ const fetchApi = async ( ) => {
20+ setState ( { data : [ ] , loading : true , error : false } ) ;
21+ try {
22+ const { data } = await accountService . getAll ( ) ;
23+ setState ( { data : data || [ ] , loading : false , error : false } ) ;
24+ } catch ( err ) {
25+ console . error ( err ) ;
26+ setState ( { data : [ ] , loading : false , error : true } ) ;
27+ }
28+ } ;
29+
30+ fetchApi ( ) ;
31+ } , [ ] ) ;
32+
33+ useEffect ( ( ) => {
34+ fetch ( ) ;
35+ } , [ fetch ] ) ;
36+
37+ return { ...state , refetch : fetch } ;
38+ } ;
You can’t perform that action at this time.
0 commit comments