I created a React custom hook named useApiRequest. I have a input component and the idea is that I want to pass the user input into the custom hook as parameter so that the custom hook fetch the data based on user input. But i can't find a way to do it without calling the custom hook inside a nested component.
Here's the custom hook code:
import {useEffect, useState} from "react"
import axios from "axios"
const useApiRequest = (url, query = '') => {
const [data, setData] = useState(null)
const [loading, setLoading] = useState(false)
const [error, setError] = useState(null)
useEffect(() => {
const fetchData = async () => {
setLoading(true)
try {
const response = await axios.get(url + query)
setData(response.data)
} catch (error) {
setError(error)
} finally {
setLoading(false)
}
}
fetchData()
}, [url, query])
return {data, loading, error}
}
export default useApiRequest
And here's the component where i use the custom hook
import SearchForm from "../UI/SearchForm"
import samplePrompt from "../../constants/text"
import Genre from "./Genre"
import { useState } from "react"
import useApiRequest from "../../hooks/use-api-request"
const Search = () => {
const [searchQuery, setSearchQuery] = useState("")
const {data, isLoading, error} = useApiRequest("some API link", searchQuery)
const searchHandler = (newValue) => {
setSearchQuery(newValue)
}
console.log(data)
return (
<div className="mx-auto flex flex-col items-center justify-center h-screen w-full">
<div className="text-center">
<h1 className="text-5xl font-poppins font-bold mt-8">Cari Anime Berdasarkan Deskripsi menggunakan Kecerdasan Buatan</h1>
<p className="mt-4">{samplePrompt[0].samplePrompt}</p>
</div>
<SearchForm searchQuery={searchQuery} onSearch={searchHandler} />
<Genre />
</div>
)
}
export default Search
I'm sorry if I didn't explain it clearly. But I hope you get the idea. Thank you