0

I have integrated Firebase/authentication with my React web app using the Javascript SDK. I setup Github sign-in using the redirect method. After a user successfully authenticates with Github, they are redirected back to my login form. I have set the listener onAuthStateChanged to my componentWillMount to push a route once a user is recognized.

I would like to show a loading icon while the onAuthStateChanged is checking the state of the user. But, I have no way of knowing that the page was called from the Firebase redirect, unless the callback includes something in the url, ie. website.com/login-form/from-firebase-callback/

any ideas on how to set this up? I have looked through the documentation but couldn't find anything. I'm hoping this is a quick config fix somewhere, as I don't want to set up the flow manually.

class LoginForm extends React.Component {
    componentWillMount() {

        // would like to add a something to the url from the firebase redirect
        const query = queryString.parse(this.props.location.search);
        if (query === 'from-firebase-callback') {
            this.isLoading = true;
        }

        const authChangedListener = auth.onAuthStateChanged((user) => {
            if (user) {
                this.loading = false;
                this.props.history.push('/dashboard/');
            } else {
                console.log('no user...');
            }
        });
    }

... rest of component
Nicholas Mueller
  • 482
  • 1
  • 6
  • 14

1 Answers1

1

Instead of getting stuck on the inability to pass state from different URLs, you could use a combination of the onAuthStateChanged listener to determine if the user is logged in or not by checking for state.user, and state.loading to keep track of the loading state.

class LoginForm extends React.Component {
    constructor(){
         super();

         this.state={
             loading:true
         }
    }

    componentWillMount() {
        firebase.auth().onAuthStateChanged((user) => {
            if (user) {
                this.setState({loading:false,user})
                this.props.history.push('/dashboard/');
            } else {
                this.setState({loading:false})
            }
        });
    }
    ... rest of component
}
turonno
  • 171
  • 4
  • thanks this works, i was overthinking it and didnt fully understand how `onAuthStateChanged` works, but the else clause does return the correct state – Nicholas Mueller Mar 19 '18 at 10:39