As an example, we'll use a component for recent orders, particularly for cryptocurrency transactions. To manage the data for recent orders, we utilize a mock API interface that simulates real-world data fetching from a server.
The
Example: Fetching Recent Orders
1function RecentOrders() {
2 const isMountedRef = useRefMounted();
3 const [cryptoOrders, setCryptoOrders] = useState<CryptoOrder[]>([]);
4
5 const getCryptoOrders = useCallback(async () => {
6 try {
7 const response = await cryptoOrdersApi.getCryptoOrders();
8 if (isMountedRef()) {
9 setCryptoOrders(response);
10 }
11 } catch (err) {
12 console.error(err);
13 }
14 }, [isMountedRef]);
15
16 useEffect(() => {
17 getCryptoOrders();
18 }, [getCryptoOrders]);
19
20 return (
21 <Card>
22 <RecentOrdersTable cryptoOrders={cryptoOrders} />
23 </Card>
24 );
25}
The
Alternatively, you could use something like
Both
1import useSWR from 'swr';
2
3function RecentOrders() {
4 const cryptoOrders = useSWR<CryptoOrder[]>(
5 '/api/crypto/orders',
6 cryptoOrdersApi.getCryptoOrders,
7 { fallbackData: [] }
8 );
9
10 return (
11 <Card>
12 {cryptoOrders.isLoading && <LoadingComponent />}
13 {cryptoOrders.error && <ErrorComponent error={cryptoOrders.error} />}
14 {cryptoOrders.data && (
15 <RecentOrdersTable cryptoOrders={cryptoOrders.data} />
16 )}
17 </Card>
18 );
19}
For the
For more information on SWR, see the SWR documentation.