I'm working on app based react+mobx and as backend use the firebase. Currently on the app start i need to check if user is logged in. I'm doing it with firebase.auth().onAuthStateChange listener, but because it's async function - the first response always null. So my current solution is display some loading message and put setInterval function with status checking in componentWillMount lifehook. The question is - is there any more elegant solution to this issue?
1 Answer
Before you call firebase.auth().onAuthStateChange, modify your state to be something like: state.authenticatedUser: 'pending'. Have your observer change that state to real user info once it is called.
Have your components take into account state.authenticatedUser when rendering and render either "authentication pending" or "authenticate user"
5 Comments
Eugene Alitz
Thank you for reply, but this solution is similar to mine, and not solve main issue - my app need to know if user is logged in or not, and pending status isn't help me.
Davorin Ruševljan
Your app will know exactly what is state of user: loged in, not logged in or being verifed, by looking into state. (you would initialize state correctly, and observer will be changing it as firebase sends notifications). It is responsibility of your components to render them selves correctly in each of those states.
Eugene Alitz
Sorry, but I don't get it. Auth listener is fired up in the store constructor. So userState will be pending at the beginning, and to listener take about 2 seconds to receive final response with auth status. So my app still wait this 2 sec before decide if user have log in. Or I missed something?
Davorin Ruševljan
Your app will not wait, during those 2 seconds it will be rendering "authenticating" or whatever. Note that during those 2 seconds no man or machine can answer if user is loged in or not, so your app is just correctly displaying what is currently known. When listener you have provided gets called, it will modify state of your app entering user info in it. State change will then automatically cause rerender of your components, their rendering code will in state find user info details, conclude that there is authorized user and render themselves accordingly.
Davorin Ruševljan
Point is that you do not wait to construct or render your components. They just render themselves differently according to the state. And your listener will change state when it hears from firebase.