0
votes

Im new to react and started using hooks but I'm receiving warning on my 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

I tried to fix it by defining a variable to check if its unmount or not(saw on another stackoverflow question. But it did not work.

here is my code

const Page1 = (props) => {
    const [averageAPICallsPerDay, setAverageAPICallsPerDay] = useState(false);
    const [org, setOrg] = useContext(OrgContext);
    const [catalog, setCatalog] = useContext(CatalogContext);
    const [didMount, setDidMount] = useState(false);

    function getAverageAPICallPerDay() {
        axios.get(`${ANALYTICS_BASEPATH}/${org}/${catalog}/analytics/calls/average`)
            .then(res => setAverageAPICallsPerDay(res.data.data.averageCalls))
            .catch(err => setAverageAPICallsPerDay('No records found'))
    }

    useEffect(() => {
        setDidMount(true);
        getAverageAPICallPerDay()

        return(didMount)
    }, [catalog, org])

    return(
        <Container>   
            <SubContainer>
                <Row>
                    <Col><Card cardTitle="Total API Calls" totalCalls={averageAPICallsPerDay}/></Col>
                </Row>
            </SubContainer>
        </Container>
    );
};
1

1 Answers

1
votes

I think the issue here might be that you are updating your state from your then or catch function once your component has been unmounted. I think you can define at the top of your effect a isCancelled variable with false, and from your effect return a function that set's it to true, and check that function in your then function.. something like this.

useEffect(() => {
  let isCanceled = false
  function getAverageAPICallPerDay() {
    axios.get(`${ANALYTICS_BASEPATH}/${org}/${catalog}/analytics/calls/average`)
        .then(res => {
          if (!isCanceled) {
            setAverageAPICallsPerDay(res.data.data.averageCalls)
          }
          })
        .catch(err => {
          if (!isCanceled) {
            setAverageAPICallsPerDay('No records found')
          }
        })
  }
  setDidMount(true);
  getAverageAPICallPerDay()

  return () => {
    isCanceled = true
  }
}, [catalog, org])