1

im trying to implement social authentication in my project and im getting this error:

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. in FaceookSignIn (created by Socials) ...

Component in question recieves code from facebook which is put into url, for redirecting.

This is the route:

<PublicRoute exact path='/:callback?' component={Auth}/>

defined as:

export const PublicRoute = ({component: Component, ...rest}) => {
  const {client, loading, data} = useQuery(GET_USER, {fetchPolicy: 'cache-only'})
  let isAuthenticated = !!data.user.accessToken

  return (
    <Route {...rest} component={(props)=>(
      isAuthenticated ? (
        <Redirect to='/home' />
      ) : (
        <Component {...props} />
      )
    )}/>
  )  
}

I've tried using hook cleanup on my component but error persists. This is what my current implementation looks like:

const FaceookSignIn = () => {
  let _isMounted = false
  const client = useApolloClient()
  const appId = '187856148967924'
  const redirectUrl = `${document.location.protocol}//${document.location.host}/facebook-callback`;

  const code = (document.location.pathname === '/facebook-callback') ? querystring.parse(document.location.search)['?code'] : null
  const [loading, setLoading] = useState(false)
  const [callFacebook, data] = useMutation(FACEBOOK_SIGN_IN)

  useEffect(()=>{
    _isMounted = true
    if(!code) return
    if(_isMounted) callFacebook({variables: {code: code}})
    .then(res=>{
      const {error, name, email, accessToken} = res.data.facebookSignIn
      if (error) {
        alert(`Sign in error: ${error}`);
      } else {
        client.writeData({
          data: {
            user: {
              name: name,
              email: email,
              accessToken: accessToken,
              __typename: 'User'
            }
          }
        })
        setLoading(false)
      }
    })
    .catch(e=>{
      console.log(e)
      setLoading(false)
    })
    return ()=> _isMounted = false
  },[])

  const handleClick = e => {
    setLoading(true)
    e.preventDefault()
    window.location.href = `https://www.facebook.com/v2.9/dialog/oauth?client_id=${appId}&redirect_uri=${encodeURIComponent(redirectUrl)}`;
  }

  return (
    <a className="login-options__link" href='/facebook-login' onClick={handleClick}>
      {loading ? <p>loading...</p> : <img className="social-link__icon" src={fb.default} id="facebook" /> }
    </a>
  )
}

This approach somewhat works, credentials are loaded and user is redirected to authenticated route but console still throws that error and ui is sometimes flicker between routes. Ive spent last two days on this and im out of ideas. Am i missing something obvious?

2
  • _isMounted isn't effective here. It doesn't tell you if your async operation callFacebook resolves after the component is unmounted. Instead of using _isMounted, cancel the callFacebook request in your cleanup handler - that way you don't call setLoading(false) after the component has unmounted.
    – Andrew Li
    Commented May 12, 2020 at 16:38
  • Thanks for the reply but setLoading isnt the culprit here, even after removing it completely im receiving same error. I was also under implression apollo queries are automatically aborted upon unmounting. Ill give a shot to cancelling it anyway and get back Commented May 12, 2020 at 17:11

1 Answer 1

0

Ok, finally figured it out, turns out I shouldn't hijack logic from apollo hooks and be careful of how data is handled. I assume mutation hook updates client state on its own, .then() block resolved before client update and unmounted component. Maybe someone can clarify?

Anyway here is updated code if anyone is interested:

const FaceookSignIn = (props) => {
  const appId = '187856148967924'
  const redirectUrl = `${document.location.protocol}//${document.location.host}/facebook-callback`
  const code = (document.location.pathname === '/facebook-callback') ? querystring.parse(document.location.search)['?code'] : null

//moved data handling logic to hooks optional callback
const [callFacebook, {client, data, loading, error, called}] = useMutation(FACEBOOK_SIGN_IN, {onCompleted: (data)=>{
    const {name, email, accessToken} = data.facebookSignIn
    client.writeData({
      data: {
        user: {
          name: name,
          email: email,
          accessToken: accessToken,
          __typename: 'User'
        }
      }
    })
  }})

  if(code && !called) {
    callFacebook({variables: {code: code}})
  }

  const handleClick = e => {
    e.preventDefault()
    window.location.href = `https://www.facebook.com/v2.9/dialog/oauth?client_id=${appId}&redirect_uri=${encodeURIComponent(redirectUrl)}`;
  }

  return (
    <a className="login-options__link" href='/facebook-login' onClick={handleClick}>
      {loading ? <p>loading...</p> : <img className="social-link__icon" src={fb.default} id="facebook" /> }
    </a>
  )
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.