Importing Dependencies & Creating the Custom Hook
import { useState, useEffect } from "react"; import axios from 'axios'; const useFetch = (endPoint, query) => { // Hook state declarations const [data, setData] = useState([]); const [error, setError] = useState(null); const [isLoading, setIsLoading] = useState(false); // Request options for the API call const options = { method: 'GET', url: `https://jsearch.p.rapidapi.com/${endPoint}`, params: { ...query }, headers: { } }; // Function to fetch data from the API const fetchData = async () => { setIsLoading(true); try { const response = await axios.request(options); setData(response.data.data); setIsLoading(false); } catch(error) { setError(error); alert("There is an error"); } finally { setIsLoading(false); } }; // Fetch data on component mount useEffect(() => { fetchData(); }, []); // Function to refetch data const refetch = () => { setIsLoading(true); fetchData(); }; // Return data, loading state, error, and refetch function return { data, isLoading, error, refetch }; }; export default useFetch;
Inside the hook, the state is managed using the useState hook. Three state variables are declared:
- data: holds the fetched data from the API.
- error: stores any error that occurs during the API request.
- isLoading: indicates whether the API call is in progress.
To use the useFetch hook in your React components
import useFetch from './useFetch'; const MyComponent = () => { const { data, isLoading, error, refetch } = useFetch('endpoint', { param1: 'value1', param2: 'value2' }); if (isLoading) { return < h3 >Loading...< /h3 >; } if (error) { return < h3 >Error: {error.message}< /h3 >; } return ( < h3 > {/* Render the fetched data */} {data.map((item) => ( < h3 key={item.id}>{item.name}< /h3 > ))} {/* Trigger the API request again */} < button onClick={refetch}>Refresh< /button > < /h3 > ); };