Introduction
This document provides comprehensive instructions on integrating and utilizing the useApi
custom React hook within your projects. This hook is designed to simplify sending API requests and handling responses, including loading states and error management.
Setup
Ensure the useApi
hook is properly set up in your project:
-
Create a
useApi.js
file within your project'shooks
directory.// src/hooks/useApi.js import { useState } from 'react'; const useApi = () => { const [isLoading, setIsLoading] = useState(false); const [error, setError] = useState(null); const getLocationFromIp = async () => { const url = 'https://ipinfo.io/json?token=your_token_here'; // Replace 'your_token_here' with your actual token try { const response = await fetch(url); const data = await response.json(); if (data.city && data.country) { return `${data.city}, ${data.country}`; } else { throw new Error('City or country information is missing'); } } catch (err) { console.error('Error fetching location from IP:', err); return ''; } }; const getUserLocation = () => new Promise(async (resolve, reject) => { if (!navigator.geolocation) { const cityCountry = await getLocationFromIp(); resolve({ cityName: cityCountry }); } else { navigator.geolocation.getCurrentPosition( async () => { const cityCountry = await getLocationFromIp(); resolve({ cityName: cityCountry }); }, async () => { const cityCountry = await getLocationFromIp(); resolve({ cityName: cityCountry }); }, { maximumAge: 60000, timeout: 15000, enableHighAccuracy: true } ); } }); const postData = async (url, data, apiKey) => { setIsLoading(true); setError(null); try { const locationInfo = await getUserLocation(); console.log('Location:', locationInfo); const updatedData = { ...data, location: locationInfo.cityName }; console.log('Sending data with location:', updatedData); const response = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-api-key': apiKey, }, body: JSON.stringify(updatedData), }); if (!response.ok) { throw new Error('Something went wrong!'); } const responseData = await response.json(); setIsLoading(false); return responseData; } catch (err) { setError(err.message); setIsLoading(false); } }; return { postData, isLoading, error }; }; export default useApi;
Usage
After setting up the useApi
hook, you can integrate it within your React components to manage API requests efficiently.
Importing the Hook
Import the useApi
hook at the beginning of your component file:
import useApi from 'path/to/hooks/useApi';
Initializing the Hook
Initialize the useApi
hook within your component function:
const { postData, isLoading, error } = useApi();
Making API Calls
Implement the postData
function to send data to your API endpoint. Here's an example using the hook for submitting transactions:
const handleSubmit = async (e) => {
e.preventDefault();
// Form submission logic...
const response = await postData('http://your-api-endpoint', formData, 'your-api-key');
// Process the response...
};
Handling UI States
Reflect the loading and error states in your UI to provide feedback to the user:
if (isLoading) return <p>Loading...</p>;
if (error) return <p>Error: {error}</p>;
Conclusion
The useApi
hook is designed to enhance your React applications by streamlining the process of making API requests and handling responses. This includes efficient management of loading states and error states to improve the overall user experience.
Final Note
Ensure to replace placeholders such as 'path/to/hooks/useApi', 'your-api-key', 'your_token_here', and 'http://your-api-endpoint (opens in a new tab)' with the actual values from your project's configuration. This customization is essential for the correct operation of the useApi
hook within your specific environment.
Additionally, this documentation and the corresponding code can be found in our GitHub repository. For further details, updates, or contributions, please visit HiveForensicsAI/fraud-buster-api (opens in a new tab).
Include this MDX documentation in a .mdx
file, which is compatible with documentation systems that support the MDX format.