fetch api(useFetch.js)
unknown
javascript
2 years ago
1.1 kB
4
Indexable
import { useEffect, useState } from "react"; import axios from "axios"; const useFetch = (endpoint, query) => { const [data, setData] = useState([]); const [isLoading, setIsLoading] = useState(false); const [error, setError] = useState(null); const options = { method: "GET", url: `https://jsearch.p.rapidapi.com/${endpoint}`, headers: { "X-RapidAPI-Key": "4bf281d16dmshe695f2c47c7bfb6p1121d9jsn61144a33a6e4", "X-RapidAPI-Host": "jsearch.p.rapidapi.com", }, params: { ...query, }, }; const fetchData = async () => { setIsLoading(true); try { const response = await axios.request(options); setData(response.data.data); setIsLoading(false); } catch (error) { setError(error); alert(error); } finally { setIsLoading(false); } }; useEffect(() => { fetchData(); }, []); const refetch = () => { setIsLoading(true); fetchData(); }; return data, isLoading, error, refetch; }; export default useFetch;
Editor is loading...