I have a dynamic URL that needs to be fetched using an axios call in useEffect hook.
const ShowData = ({country}) => {
const [searchResult, setSearch] = useState([])
const url = `https://restcountries.com/v3.1/name/${country}`
useEffect((url) => {
axios.get(url)
.then(response => {
setSearch(response.data)
})
}, [])
return (
<div>
<Data data={searchResult}/>
</div>
)
}
When using url inside the useEffect hook, it says React Hook useEffect has a missing dependency. How do I use the URL inside the hook?
>Solution :
Since you are creating url based on country, Actually you need to pass country as one of useEffect dependencies and move url definition inside the effect body, so whenever country has changed, your effect will run. like this:
useEffect(() => {
const url = `https://restcountries.com/v3.1/name/${country}`
axios.get(url)
.then(response => {
setSearch(response.data)
})
}, [country])