0

I'm using Axios to perform a couple of API queries in order to fetch some data to be displayed in my React App.

On the first page load I receive the following warning in the console:

Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

After a bit of research I found where the problem was: in the "init" API call. The same call is repeated during the application usage as "polling" requests, but in this case the error doesn't show up.

The code is the following:

  // First API call to init data
  useEffect(() => {
    initAPI()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);


  function initAPI() {
    apiV2.getData1()
     .then((response) => {
      setData1(response.data.all)
    apiV2.getData2()
      .then((response) => {
        setData2(response.data.all)
      })
      .catch((error) => {
        console.log(error)
      })
  })
  .catch((error) => {
    console.log(error)
  })
}

If I comment the setData1/2 the problem disappears.

Finally, the axios usage:

import axios from "axios"

const client = axios.create({
  // baseURL: "http://127.0.0.1:8000/api"
  // baseURL: "http://localhost:3000/"
  baseURL: process.env.REACT_APP_BACKEND_SERVER,
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json' 
  }
});


export default {

  getData1: () =>
    client({
      'method': 'GET',
      'url': '/data1',
      transformResponse: [function (data) {
        const json = JSON.parse(data)
        data = {
          rates: json
        }
        return data
      }],
    }),
 }

Is there a way to avoid this issue?

user840718
  • 1,563
  • 6
  • 29
  • 54
  • Does this answer your question? [How to fix React WArning : Can't perform a React state update on an unmounted component](https://stackoverflow.com/questions/71258604/how-to-fix-react-warning-cant-perform-a-react-state-update-on-an-unmounted-co) – Cesare Polonara May 23 '22 at 10:58
  • You need to abort the axios call in the clean up function of the useEffect, but in any case that warning is removed in React18 https://github.com/facebook/react/pull/22114 – Cesare Polonara May 23 '22 at 11:00

0 Answers0