Skip to content

Commit 70eb54e

Browse files
committed
feat: implement useAccounts hook for managing account data fetching and state
1 parent eca12e5 commit 70eb54e

1 file changed

Lines changed: 38 additions & 0 deletions

File tree

client/src/hooks/useAccounts.tsx

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
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+
};

0 commit comments

Comments
 (0)