# 3.5: Checking Authentication and User Status

You, of course, have noticed that every time we make a change and restart the app, we have to sign in again. Not only is that slow for development, it makes for a terrible user experience (UX). Let's improve that and also make sure that we route users with no profile image to add one, and route those who do have one to our 'Home' screen.

Firebase gives us several authorization methods. The one that will best fit us is `onAuthStateChanged`. When we open the app, firebase will check to see if we are currently logged in on this device (firebase records that for us, very convenient). It is asynchronous.

To do this, we will create a new screen called 'LoadingScreen'. Go ahead and create a new /loadingScreen folder with an index.js file (don't worry about the styles.js, we will be using only one line of style for this file). In addition, let's go ahead and rename LandingPage to Login. Update the App.js page in the StackNavigator and the import at the top. Sometimes, when changing the routing of screens, you need to restart Expo to fix errors.

Note: When adding Loading into our list of screens, make sure you add it to the very top!

Let's go ahead and import what we do for every screen, along with firebase and the JSX expressions we will be using:

```jsx
import React, { Component } from 'react';
import commonColor from './../../theme/commonColor';
import firebase from 'firebase';
import { View, ActivityIndicator } from 'react-native';
```

Now we can set up our render method:

```jsx
export default class LoadingScreen extends Component {

    render = () => {
        return (
            <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
                <ActivityIndicator
                    size="large"
                    color={commonColor.brandPrimary}
                />
            </View>
        )
    }
}
```

\
&#x20;`justifyContent: 'center'` moves the view down to the middle of the screen vertically, and `alignItems: 'center'` moves it to the center horizontally.

For our firebase method, we are going to use the componentDidMount lifecycle method. We are doing this because we want the component to mount and show the loading indicator as soon as possible; we don't need to wait on any information in a componentWillMount, for example. Remember, onAuthStateChanged is asynchronous -- if our connection is slow, we want the loading indicator to show. Although `onAuthStateChanged` usually runs very quickly, we often need to grab some other information during loading (although we aren't here), and we want users to know the app is still running.

```jsx
componentDidMount = async () => {
        await firebase.auth().onAuthStateChanged(user => {
            if (user) {
                ...check if user has a picture, route accordingly
            } else {
                this.props.navigation.navigate('Login')
            }
        })
    }
```

Simple enough. If we have a user, we want to check if there is a picture associated with that account, if no user is logged in, then we navigate to the 'Login' Page (formerly the landing page).

If there is a user, we want to check firebase for a picture url.

```jsx
if (user) {
let uid = user.uid
firebase.database().ref('userInformation').child(uid).child('profImage').once('value')
```

We then use a `.then` promise with the response. If any information comes back, we route home.

```jsx
.then(res => {
    if (res) {
        this.props.navigation.navigate('Home', { uid })
    } else {
        this.props.navigation.navigate('FinishProfile', { uid })                        
    }
})
```

It would seem intuitive that we also need to make this change in our signin function from /login.index.js to something like this:

```jsx
firebase.auth().signInWithEmailAndPassword(this.state.signinEmail, this.state.signinPassword)
    .then(res => {
        let uid = res.uid
        firebase.database().ref('userInformation').child(uid).child('profImage').once('value')
        .then(res => {
            if (res) {
                this.props.navigation.navigate('Home', { uid })
            } else {
                this.props.navigation.navigate('FinishProfile', { uid })                        
            }
        })
    })
```

Making this change, however, leads to unwanted behavior. It would be easy to miss at this point, considering we haven't set up signing out yet, but if you were to sign out and back in, you would see the Home page render twice. Let's examine why. We have our newly set up `onAuthStateChanged`. When we sign in, the auth state changes. So BOTH firebase methods are trying to route the user to the Home page or the FinishProfile page. The `signin` function tries to route the user to Home, then the `onAuthStateChanged` listener tries to do the same. So instead of making the change like above, we want to actually strip the signin function of routing, allowing our firebase authorization listener to handle all routing.

```jsx
signin = () => {
    firebase.auth().signInWithEmailAndPassword(this.state.signinEmail, this.state.signinPassword)
    .catch(res => {
        console.log('error ', res.code)
    })
}
```

We will do the same with signup, as the firebase authorization listener also runs when we sign up.

```jsx
signup = () => {
    if (this.state.signupPassword == this.state.signupConfirmPassword) {
        firebase.auth().createUserWithEmailAndPassword(this.state.signupEmail, this.state.signupPassword)
        .then(res => {
            let uid = res.uid
            let userInfo = {
                username: this.state.signupUsername
            }
            firebase.database().ref('userInformation').child(uid).set(userInfo)
        })
        .catch(res => {
            console.log('error ', res)
        })
    }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://eleven-fifty-academy.gitbook.io/javascript-301-reactnative-gitbook/part-3-navigation-tab-navigator/3.5-checking-authentication-and-user-status.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
