Search code examples
androidreact-nativeaxiosuse-effect

Maximum Update Depth Exceeded axios


The useEffect below is causing the following error: Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render. Consequently I get a white screen when I run my app on the emulator. The code works fine when I use sample data instead of the useEffect. KEY is replaced by my actual key and the link works because I tested it in the browser and is how I obtained the sample data. How can this issue be solved?

    const [data, setData] = useState()
    const [rates, setRates] = useState()
   const [baseCurrencies, setBases] = useState();
   const [resultCurrencies, setResult] = useState();

       
     useEffect(() => {
          const fetchData = async () => {
            const response = await axios.get('https://api.apilayer.com/exchangerates_data/latest?apikey={KEY IS HERE}&base=EUR')
            const data = response.data
            if(data){
              setData(data)
              setRates(data.rates)
              setBases(getSymbols(data))
              setResult(getSymbols(data))
            }
          }
          fetchData()
        }, [])

Solution

  • This issue was solved by putting the following lines into a useMemo with data as a dependency instead of inside the useEffect:

    setRates(data.rates)
    setBases(getSymbols(data))
    setResult(getSymbols(data))