0

I'd like to simulate fetching data inside useEffect hook, but I'm getting warning: React Hook useEffect has a missing dependency: 'fetchData'.

Since I wanted to call this fetch function only once, it should work fine. Can you help me?

I "fetch" data from local array

const people = [
    { id: 1, name: 'Alex' },
    { id: 2, name: 'Ben' },
  ];

//useState hook where I want to keep fetched data

const [data, setData] = useState([]);

//simulated fetch data function

const fetchData = () => {
    setTimeout(() => {
      people.forEach(item => {
        setData(currentState => [...currentState, item]);
      })
    }, 500);
  };

//finally useEffect hook

useEffect(() => {
    fetchData();
}, []);
  • 1
    Does this answer your question? [How to fix missing dependency warning when using useEffect React Hook?](https://stackoverflow.com/questions/55840294/how-to-fix-missing-dependency-warning-when-using-useeffect-react-hook) – Kipnoedels Jun 14 '21 at 11:54

1 Answers1

0

There can be two possible fixes:

  1. Include fetchData fn into useEffect that way it wont complain about dependencies.
  2. Include fetchData fn into the dependency array and that would also run on component mount.
PRATIK NAIK
  • 489
  • 3
  • 7