1

I'm building a webapp with react and i get this warning:

src\Containers\App.js
  Line 30:6:  React Hook useEffect has a missing dependency: 'API_KEY'. Either include it or remove the dependency array  react-hooks/exhaustive-deps
  Line 36:6:  React Hook useEffect has a missing dependency: 'API_KEY'. Either include it or remove the dependency array  react-hooks/exhaustive-deps

Here the App.js code:

import React, { useState, useEffect } from 'react';
import './App.css';
import 'tachyons';

const App = () => {

  const API_KEY = `...`;

  const [searchField, setSearchField] = useState('');
  const [countryField, setCountryField] = useState('');  
  const [currentData, setCurrentData] = useState(null); 
  const [oneCallData, setOneCallData] = useState(null); 

  useEffect(() => { 
    fetch(`https://api.openweathermap.org/data/2.5/weather?q=Cinisi&units=metric&appid=${API_KEY}`)
      .then(resp => resp.json())
      .then(dataRecived => {
        setCurrentData(dataRecived);
      })
  }, []);

  useEffect(() => {
    fetch(`https://api.openweathermap.org/data/2.5/onecall?lat=38.1562&lon=13.1073&units=metric&exclude=current,minutely,alerts&appid=${API_KEY}`)
      .then(resp => resp.json())
      .then(dataRecived => setOneCallData(dataRecived))
  }, []);
...


  

thank in advance anyone who tries to give me an answer

Saverio Randazzo
  • 217
  • 1
  • 7
  • 19
  • See this https://stackoverflow.com/questions/55840294/how-to-fix-missing-dependency-warning-when-using-useeffect-react-hook and https://namespaceit.com/blog/how-to-fix-missing-dependency-warning-when-using-useeffect-react-hook – DineshMsd Aug 12 '21 at 17:03

1 Answers1

0

I suggest that type of refactoring: Component should have only one useEffect.

Where fetchData1 and fetchData2 should have more meaningfull names.

  const fetchData1 = useCallback(() => {
    fetch(`https://api.openweathermap.org/data/2.5/onecall?lat=38.1562&lon=13.1073&units=metric&exclude=current,minutely,alerts&appid=${API_KEY}`)
      .then(resp => resp.json())
      .then(dataRecived => setOneCallData(dataRecived))
  }, [API_KEY]);

  const fetchData2 = useCallback(() => {
    fetch(`https://api.openweathermap.org/data/2.5/weather?q=Cinisi&units=metric&appid=${API_KEY}`)
      .then(resp => resp.json())
      .then(dataRecived => {
        setCurrentData(dataRecived);
      })
  }, [API_KEY]);


  useEffect(() => { 
    fetchData1()
    fetchData2()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
Piotr Żak
  • 2,046
  • 5
  • 18
  • 30