API Calls


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.

Fetching Data with useRefMounted and useEffect

useRefMounted
is a custom hook that returns a function to check if the component is still mounted, which helps avoid state updates on unmounted components.

useEffect
is used to call the getCryptoOrders function when the component mounts.

Mocking API Calls with cryptoOrdersApi

cryptoOrdersApi
is a mock class that simulates fetching data from an API.

getCryptoOrders
method in the
CryptoOrdersApi
class returns a Promise that resolves with an array of crypto orders.

Handling Data Types with TypeScript

The

CryptoOrder
type is defined in
src/models/crypto_order.ts
to strongly type the expected structure of an order.

getCryptoOrders
method in the Use this type to define the state and handle the fetched data, ensuring type safety.

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}
Simulating API Responses

The

CryptoOrdersApi
class uses hardcoded data to simulate an API response. This is helpful during development before the backend API is available. Once the actual API is ready, replace the mock logic with real API calls.



Using SWR

Alternatively, you could use something like

swr
or
react-query
as a more simple solution.

Both

swr
and
react-query
are React Hooks libraries used for data fetching.

Example integration with SWR
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

ErrorComponent
and
LoadingComponent
you could use examples from the UIFort components Alerts, Empty states or Skeleton loading.

For more information on SWR, see the SWR documentation.