简体   繁体   中英

Invalid exhaustive deps in react hooks

I am using a react hook to fetch the data from covid api using axios but it throws an error of

React Hook useEffect has a missing dependency: 'countries'. Either include it or remove the dependency array  react-hooks/exhaustive-deps

where countries is my state

Code:

const [countries,setCountries]=useState([]);

  useEffect(()=>{
    axios.get('https://disease.sh/v3/covid-19/countries').then(response=>{
      //console.log(response.data);
      setCountries(response.data);
      console.log(countries);
    }).catch((error)=>{
      console.log(error);
    })

  },[]);

I have tried doing every solutions provided by other forums but this is prefectly fine mentioned by some solutions. Why isnt this code working?

If you use countries in your hook, you should add it to your deps. Otherwise you will read a stale value because the state value countries was not yet updated:

useEffect(()=>{
    axios.get('https://disease.sh/v3/covid-19/countries').then(response=>{
      //console.log(response.data);
      setCountries(response.data);
      console.log(countries);
    }).catch((error)=>{
      console.log(error);
    })
  },[countries]);

However in your case I would advice against adding countries to your deps , because you also call setCountries in your hook. This way your hook would be entered again because countries has changed. You should rather log the value of countries outside of your hook if you need it.

console.log(countries);

useEffect(()=>{
    axios.get('https://disease.sh/v3/covid-19/countries').then(response=>{
      //console.log(response.data);
      setCountries(response.data);
    }).catch((error)=>{
      console.log(error);
    })
  },[]);

If you are adding any variables which can be changed in useEffect it will ask you to update the dependency array.You are logging countries that's why you are seeing this warning.

If you want to understand useEffect in depth, and about the dependency array blog by Dan Abramov about A complete Guide To Useeffect will be very helpful

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM