How do I fix “useEffect has a missing dependency” in custom hook

末鹿安然 提交于 2021-02-16 20:24:09

问题


I'm using a custom hook to get pull some data in from an API for use across a set of React function components. However, esLint throws up a lovely warning:

React Hook useEffect has a missing dependency: 'fetchFromAPI'. Either include it or remove the dependency array.

I didn't think it's a dependency, as it's inside useFetch() itself. I need to do it as I'm using await. What am I doing wrong? Is it ok to just turn off the warning for this line? Or is there a more canonical syntax I should be using?

function useFetch (url) {
  const [data, setData] = useState(null);

  async function fetchFromAPI() {
    const json = await( await fetch(url) ).json();
    setData(json);
  }

  useEffect(() => {fetchFromAPI()},[url]);

  return data;
};

export {
  useFetch
};

回答1:


I suggest you to define async function inside useEffect itself:

function useFetch (url) {
  const [data, setData] = useState(null);
  useEffect(() => {
    async function fetchFromAPI() {
      const json = await( await fetch(url) ).json();
      setData(json);
    }
    fetchFromAPI()
  },[url]);

  return data;
};

You can take a look at valid example from doc faqs which uses async function inside useEffect itself:

function ProductPage({ productId }) {
  const [product, setProduct] = useState(null);

  useEffect(() => {
    // By moving this function inside the effect, 
    // we can clearly see the values it uses.
    async function fetchProduct() {
      const response = await fetch('http://myapi/product' + productId);
      const json = await response.json();
      setProduct(json);
    }

    fetchProduct();
  }, [productId]); // ✅ Valid because our effect only uses productId
  // ...
}



回答2:


Declare it outside your custom effect passing url as parameter and return the json to be setted inside useEffect

async function fetchFromAPI(url) {
    const json = await( await fetch(url) ).json();
    return json
}

function useFetch (url) {
  const [data, setData] = useState(null);

  useEffect(() => {
      setData(fetchFromAPI(url))
  },[url]);

  return data;
};

Or directly inside useEffect

function useFetch (url) {
  const [data, setData] = useState(null);

  useEffect(() => {
      async function fetchFromAPI() {
         const json = await( await fetch(url) ).json();
         return json
      }
      setData(fetchFromAPI())
  },[url]);

  return data;
};



回答3:


Just move your function inside the useEffect, and everything will be fine:

import { useState, useEffect } from "react";

function useFetch(url) {
  const [data, setData] = useState(null);

  useEffect(() => {
    async function fetchFromAPI() {
      const json = await (await fetch(url)).json();
      setData(json);
    }
    fetchFromAPI();
  }, [url]);

  return data;
}

export { useFetch };

https://codesandbox.io/s/clever-cdn-8g0me




回答4:


async function fetchFromAPI(url) {
  return ( await fetch(url) ).json();
}

function useFetch (url) {
  const [data, setData] = useState(null);

  useEffect(() => {
    fetchFromAPI(url).then(setData);
  }, [url, setData, fetchFromAPI]);

  return data;
};

export {
  useFetch
};
  1. You can change a little and then extract fetchFromAPI, for not being created every time useFetch calls, also it's good for single responsibility.
  2. If you understand this code very well of course you can either turn off linting for this current line or you can add the rest setData and fetchFromAPI params. And exactly in this order. Because on re-render params comparison start from first param to last, and it's better place most changed param in first place, for not checking not changed param every time the next one is changed, so if first changed, useEffect don't need to check the others and call passed function earlier


来源:https://stackoverflow.com/questions/58413705/how-do-i-fix-useeffect-has-a-missing-dependency-in-custom-hook

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!