React Hook useEffect has a Missing dependency: .... Either include it or remove the dependency array React-Hooks/exhaustive-deps

Asked

Viewed 16,832 times

4

I’m getting the following warning when using the hook useEffect:

React Hook useEffect has a Missing dependency: 'connect'. Either include it or remove the dependency array React-Hooks/exhaustive-deps.

I looked at some tutorials on the internet, but I couldn’t find any way out that worked. What am I doing wrong? Follow the problematic code:

const Grafico = (props) => {
  const [estoqueReal, setEstoqueReal] = useState([]);
  const [estoquePrevisto, setEstoquePrevisto] = useState([]);
  const [data, setData] = useState([]);
    
  async function conectar() {
    const resposta = await ObterEstoque(props);

    setEstoqueReal(resposta[0])
    setEstoquePrevisto(resposta[1])
    setData(resposta[2])
    }

  useEffect(() => {
    conectar()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (...);

2 answers

6


The problem here is that it is not clear to use external methods within the useEffect event as it will be more complicated to map out what effect information needs to be executed.

All variables and methods must be declared in the array.

The following article explains this question in more detail and examples: https://reactjs.org/docs/hooks-faq.html#is-it-safe-to-omit-functions-from-the-list-of-dependencies

In your case just put the connect method inside the useEffect as below:


   useEffect(() => {
      async function conectar() {
         const resposta = await ObterEstoque(props);

         setEstoqueReal(resposta[0])
         setEstoquePrevisto(resposta[1])
         setData(resposta[2])
      }
      await conectar();
      }, [props]);

0

Just put the connect in the array, for example:

const Grafico = (props) => {
  const [estoqueReal, setEstoqueReal] = useState([]);
  const [estoquePrevisto, setEstoquePrevisto] = useState([]);
  const [data, setData] = useState([]);

  async function conectar() {
    const resposta = await ObterEstoque(props);

    setEstoqueReal(resposta[0])
    setEstoquePrevisto(resposta[1])
    setData(resposta[2])
    }

  useEffect(() => {
    conectar()
  }, [conectar]);

  return (...);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.