mirror of
https://github.com/urosran/cally.git
synced 2025-11-26 00:24:53 +00:00
Update logic for profile creation
This commit is contained in:
81
contexts/AuthContext.tsx
Normal file
81
contexts/AuthContext.tsx
Normal file
@ -0,0 +1,81 @@
|
||||
import {createContext, FC, ReactNode, useContext, useEffect, useState} from "react";
|
||||
import * as SplashScreen from "expo-splash-screen";
|
||||
import auth, {FirebaseAuthTypes} from "@react-native-firebase/auth";
|
||||
import {useRouter} from "expo-router";
|
||||
import firestore from "@react-native-firebase/firestore";
|
||||
import {UserProfile} from "@/hooks/firebase/types/profileTypes";
|
||||
|
||||
type ProfileType = "parent" | "child" | "caregiver" | null;
|
||||
|
||||
interface IAuthContext {
|
||||
user: FirebaseAuthTypes.User | null,
|
||||
profileType?: ProfileType,
|
||||
profileData?: UserProfile
|
||||
setProfileData: (profileData: UserProfile) => void
|
||||
}
|
||||
|
||||
const AuthContext = createContext<IAuthContext>(undefined!)
|
||||
|
||||
export const AuthContextProvider: FC<{ children: ReactNode }> = ({children}) => {
|
||||
const [user, setUser] = useState<FirebaseAuthTypes.User | null>(null)
|
||||
const [initializing, setInitializing] = useState(true);
|
||||
const [profileType, setProfileType] = useState<ProfileType | undefined>(undefined);
|
||||
const [profileData, setProfileData] = useState<UserProfile | undefined>(undefined);
|
||||
|
||||
const {replace} = useRouter()
|
||||
const ready = !initializing
|
||||
|
||||
const onAuthStateChanged = async (user: FirebaseAuthTypes.User | null) => {
|
||||
setUser(user);
|
||||
|
||||
if (user) {
|
||||
try {
|
||||
const documentSnapshot = await firestore()
|
||||
.collection("Profiles")
|
||||
.doc(user.uid)
|
||||
.get();
|
||||
if (documentSnapshot.exists) {
|
||||
setProfileType(documentSnapshot.data()?.profileType);
|
||||
setProfileData(documentSnapshot.data() as UserProfile)
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error("Error fetching user profile type:", error);
|
||||
setProfileType(null);
|
||||
}
|
||||
}
|
||||
|
||||
if (initializing) setInitializing(false);
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
const subscriber = auth().onAuthStateChanged(onAuthStateChanged);
|
||||
return subscriber;
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!initializing) {
|
||||
SplashScreen.hideAsync();
|
||||
}
|
||||
}, [initializing]);
|
||||
|
||||
useEffect(() => {
|
||||
if (ready && user) {
|
||||
replace({pathname: "/(auth)"})
|
||||
} else if (ready && !user) {
|
||||
replace({pathname: "/(unauth)"})
|
||||
}
|
||||
}, [user, ready]);
|
||||
|
||||
if (!ready) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{user, profileType, profileData, setProfileData}}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
export const useAuthContext = () => useContext(AuthContext)!;
|
||||
Reference in New Issue
Block a user