Ragu
Ragu

Reputation: 155

Cannot set state in useEffect

I am trying to get the result from the session and set its state in my react component. But every time I am getting the memory leak problem due to which I am unable to set my session status to true.

My useEffect code looks like this:

useEffect(() => {
 let mounted = true;
  getSession()
    .then(session => {
      console.log('session: ', session);
      if (mounted) {
      setStatus(true);
     }
    })
    .catch(e => {
      console.log('inside error or no session found');
      console.log(e);
    });

 return () => {
   mounted = false;
 };
}, [status, getSession]);

I tried these methods to solve my problem: Boolean Flag to Control the useEffect and AbortController to clean the useEffect, but both of them did not work.

can you please suggest what is going wrong?

Upvotes: 0

Views: 135

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074138

The name of your mounted variable suggests you're expecting that effect callback to only fire on first mount, and the cleanup to only fire on dismount, but your dependency array ensures that the cleanup and effect callback happen every time status or getSession changes.

You don't use status in the callback, so you should remove that to avoid triggering the effect when setting it true. If getSession is stable (doesn't change) across the life of the component, you can remove that as well. Then, with an empty dependency array, your callback will only get called on mount, and your cleanup will only get called on dismount.


Just a side note: If you can modify getSession to accept an AbortSignal you can use to tell it to cancel its operation proactively, in general that's preferable. For instance, if you were using fetch (perhaps getSession does under the covers?), you could do that because fetch accepts an AbortSignal. Details: fetch, AbortController, AbortSignal

Upvotes: 1

Related Questions