Reputation: 990
I have a uid from firebase, but it is stored like this:
checkout.js
firebase.auth().onAuthStateChanged((user) => {
if(user) {
console.log(user.uid)
}
});
the user.uid
stores the uid I need to pass to another page. this uid is stored in checkout.js
, and I need to get it to profile.js
to use the uid there. how would I do this?
please let me know if more code is needed. I am using react / js
Upvotes: 1
Views: 51
Reputation: 13588
use a context store
create the store and the hook
const FirebaseAuthContext = createContext()
export function useAuth() {
const context = useContext(FirebaseAuthContext)
if (!context && typeof window !== 'undefined') {
throw new Error(`useAuth must be used within a FirebaseAuthContext`)
}
return context
}
Create the Provider
export function FirebaseAuthProvider(props) {
const [authState, setAuthState] = useState({
isLoggedIn: false,
currentUser: null,
pending: true,
})
useEffect(() => {
const unregisterAuthObserver = auth().onAuthStateChanged(async (currentUser) => {
if (currentUser) {
setAuthState({. isLoggedIn: true, pending: false, currentUser})
} else {
setAuthState({ ...authState, currentUser: null, pending: false })
}
})
return () => unregisterAuthObserver()
}, [])
return <FirebaseAuthContext.Provider value={authState}>{props.children}</FirebaseAuthContext.Provider>
Wrap your app with provider
<FirebaseAuthProvider><App /></FirebaseAuthProvider>
Then wherever you need to validate the user.
const { currentUser, pending } = useAuth();
if (currentUser && pending) //pending authentication
if (currentUser) // user is login, uid is in currentUser.uid
Upvotes: 1
Reputation: 990
I literally just copy and pasted that code into the profile.js
and it worked. 😑
Upvotes: 1