const { uid, phoneNumber, signOut } = useDoormanUser()
So, here you are. You've successfully added phone authentication to your app. You did it.
And now, you're wondering, how do I access the current user inside my authenticated app? 🧐
Before Doorman, this was actually a challenge.
You need access to the current user's details, such as their unique id (uid
) and perhaps their phone number (phoneNumber
). And you also need your components to re-render whenever these change, to make sure there's no stale data.
With Doorman, accessing the current user is easy.
You can either use useDoormanUser
or withDoormanUser
, depending on your preference for React Hooks vs higher order components.
import React from 'react'import { Text } from 'react-native'import { useDoormanUser } from 'react-native-doorman'const UserDetails = () => {const { uid, phoneNumber, signOut } = useDoormanUser()return <Text>uid: {uid}, phone: {phoneNumber}</Text>}export default UserDetails
import React from 'react'import { Text } from 'react-native'import { withDoormanUser } from 'react-native-doorman'function UserDetails(props) {// receives a user propconst { phoneNumber, uid } = props.userreturn <Text>uid: {uid}, phone: {phoneNumber}</Text>}export default withDoormanUser(UserDetails)
import React from 'react'import { Text } from 'react-native'import { withDoormanUser } from 'react-native-doorman'class UserDetails extends React.Component {render() {// access via this.props.userconst { phoneNumber, uid } = this.props.userreturn <Text>uid: {uid}, phone: {phoneNumber}</Text>}}export default withDoormanUser(UserDetails)
There is one important caveat for these functions, as mentioned on the useDoormanUser
page:
useDoormanUser
and withDoormanUser
should only be used on screens/components that show up after a user has signed in. If you use either of these when a user hasn't authenticated yet, it will throw an error.
If you want to access the user on a screen where a user may or may not be signed in, then use useMaybeDoormanUser
instead:
import React from 'react'import { Text } from 'react-native'import { useMaybeDoormanUser } from 'react-native-doorman'const MaybeUserDetails = () => {const [user, signOut] = useMaybeDoormanUser()// check if the user is defined or not firstif (!user) {// if it isn't, then no one is signed in yet!return <Text>Not signed in yet!</Text>}// Ok, now we now there is a user! 🔥const uid = user.uidconst phoneNumber = user.phoneNumberreturn <Text>uid: {uid}, phone: {phoneNumber}</Text>}export default MaybeUserDetails