简体   繁体   中英

How to fix missing dependency warning when using useEffect Hook

How I'm currently using useEffect() (which I only want to run once in the beginning similar to componentDidMount()):

useEffect(() => {
    fetchBusinesses();
  }, []);
const fetchBusinesses = () => {
    return fetch("theURL", {method: "GET"}
    )
      .then(res => normalizeResponseErrors(res))
      .then(res => {
        return res.json();
      })
      .then(rcvdBusinesses => {
        // some stuff
      })
      .catch(err => {
        // some error handling
      });
  };

There are multiple ways to handle such warnings.

  1. As @ Yousaf said, just add the whole function inside your useEffect.
useEffect(() => {
function fetchBusinesses() {
...
}
fetchBusinesses()
}, []);
  1. You can make use of useCallback()
    const fetchBusinesses = useCallback(() => {
      ...
    }, [])
    useEffect(() => {
      fetchBusinesses()
    }, [fetchBusinesses]);
useEffect(() => { const fetchBusinesses = () => { return fetch("theURL", {method: "GET"}) .then(res => normalizeResponseErrors(res)) .then(res => { return res.json(); }) .then(rcvdBusinesses => { // some stuff }) .catch(err => { // some error handling }); }; fetchBusinesses(); }, [])

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