DEV Community

Discussion on: React Firebase Authentication

Collapse
 
cdock profile image
Conor Dockry

I would get rid of auth.js. Seems like extra indirection for not much gain.

You can refactor action in the form:

<Form
      action={firebase.auth().signInWithEmailAndPassword}
      title="Login"
      onSuccess={() => props.history.push('/dashboard')}
      onError={({ message }) => context.setMessage(`Login failed: ${message}`)}
    />

Enter fullscreen mode Exit fullscreen mode

Then in Form.js

handleSubmit(event) {
    event.preventDefault();
    const {
      email,
      password,
      props: { action }
    } = this;

   action(
      email.current.value,
      password.current.value
    ).then(this.handleSuccess).catch(this.handleErrors);
  }

Enter fullscreen mode Exit fullscreen mode

I recently made something similar using React.Context to manage auth state. On some advice from @kentcdodds he made a point how, if your entire app depends on an authorized user, it's much easier to handle it all in it's own module then just import user state in the files that need it, in the Components that are only rendered for an authorized user.

With firebase auth I'm just rendering a complete different root Component (App or Login) in my main index file like this:

const renderApp = () => {
  ReactDOM.render(<App />, root)
}
const renderLogin = () => {
  ReactDOM.render(<Login />, root)
}

firebase
  .firestore()
  .enablePersistence()
  .then(() => {
    firebase.auth().onAuthStateChanged(user => {
      if (user) {
        renderApp()
      } else {
        renderLogin()
      }
    })
  })

Enter fullscreen mode Exit fullscreen mode

But this could also be renderApp(user) and you could define routes appropriately in there. Easier to not have to check for user everywhere, and in each Component you can just:

import firebase from '../firebase'

....

const user = firebase.auth().currentUser 
Enter fullscreen mode Exit fullscreen mode

where needed, knowing the user is logged in at this point.