Am using Firebase PhoneAuth for authentication in my ReactNative app and am coding my own {NodeJS, Express, MongodDB} server application for the API.
So the idea is, my app authenticates the user via the Firebase authentication, and upon successful authentication, will have the Token generated by Firebase. And this Token will be used to make any API calls to my server. And this Token is validated at my server and the corresponding response is provided.
I already asked a question about storing the Token, and Doug told me that I should listen to the onIdTokenChanged in each & every page and use the Token from there to make the API calls to my server.
Here's my minimal code:
import React from 'react'
import {View, Text} from 'react-native'
import auth from '@react-native-firebase/auth'
export default function Home({ navigation })
{
auth().onIdTokenChanged(function(user) {
if (user) {
user.getIdToken().then( token => {
console.log( token )
});
}
});
return (
<View>
<Text>Hello</Text>
</View>
)
}
Am new to ReactNative and NodeJS. So am trying to code everything properly.
My questions are:
- This is an asynchronous request isn't it? I mean the fetching of the Token. So I should display a Loader in the screen by default at startup, and inside the
user.getIdToken().then( token=>{ //hide the loader })I should hide the Loader, and make the API call to my server? - If I want to make another(different) API call from the same screen, should I have to listen to this
onIdTokenChangedand get the Token and then make the new API call to my server? Or should I store the previously fetched Token to a state variable usinguseStateand then use this stored Token in the subsequent API calls from the same screen? - As you can see in my minimal code, my code for listening to
onIdTokenChangedis before the rendering of the screen. Should I have to move it to theuseEffect()function instead? If I moved it, do I have to unsubscribe anything inside it?