Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React useEffect: Use data not defined as parameter

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading