the-road-to-react-with-firebase / react-firebase-authentication

🔥 Boilerplate Project for Authentication with Firebase in React.
https://www.robinwieruch.de
1.01k stars 296 forks source link

A quick question and a thank you! #45

Closed codequistador closed 3 years ago

codequistador commented 3 years ago

First of all, thank you for this excellent tutorial. I have a full-cycle auth app up and running and it was fun and easy to do!

Second, I am using the hooks api for most of the meat of my app (still using withFirebase as a HOC)... in the step where we save the authUser state to App you added a componentWillUnmount to reset the listener. I got lost at this step... here is my implementation:

const App = (props: Props) => {
  const [authUser, setAuthUser] = useState(null)

  useEffect(() => {
    props.firebase.auth.onAuthStateChanged((authUser: any) => {
      authUser ? setAuthUser(authUser) : setAuthUser(null)
    })
  })

  return (
    <ChakraProvider theme={theme}>
      <Router>
        <Navigation authUser={authUser} />

        <hr />
        ...
      </Router>
    </ChakraProvider>
  )
}

Is there potential for memory leakage here?

Thanks again!

Justin

codequistador commented 3 years ago

I should have read @timvanmourik's PR before posting this. I think it is sorted with his approach.

const [authUser, setAuthUser] = useState(
    JSON.parse(localStorage.getItem('authUser') as string)
  )

  useEffect(() => {
    const unsubscribe = props.firebase.auth.onAuthStateChanged(
      (authUser: any) => {
        localStorage.setItem('authUser', JSON.stringify(authUser))
        setAuthUser(authUser)
      },
      () => {
        localStorage.removeItem('authUser')
        setAuthUser(null)
      }
    )
    return () => unsubscribe()
  })