Reactjs – React Hook useEffect has a missing dependency: ‘list’

react-hooksreactjs

Once I run the below code, I get the following error:

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

I cannot find the reason for the warning.

import React, { useState, useEffect } from 'react';
import axios from 'axios';
import Form from './Form';

const App = () => {
  const [term, setTerm] = useState('pizza');
  const [list, setList] = useState([]);

  const submitSearch = e => {
    e.preventDefault();
    setTerm(e.target.elements.receiptName.value);
  };

  useEffect(() => {
    (async term => {
      const api_url = 'https://www.food2fork.com/api';
      const api_key = '<MY API KEY>';

      const response = await axios.get(
        `${api_url}/search?key=${api_key}&q=${term}&count=5`
      );

      setList(response.data.recipes);
      console.log(list);
    })(term);
  }, [term]);

  return (
    <div className="App">
      <header className="App-header">
        <h1 className="App-title">Recipe Search</h1>
      </header>
      <Form submitSearch={submitSearch} />
      {term}
    </div>
  );
};

export default App;

Best Answer

Inside your useEffect you are logging list:

console.log(list);

So you either need to remove the above line, or add list to the useEffect dependencies at the end. so change this line

}, [term]);

to

}, [term, list]);
Related Topic