I'm encountering an error in my useCachedResources.ts file and I'm uncertain of the cause. These three files are what I'm currently working with. I have a suspicion that the issue lies in the initial null value, but I am conditionally rendering my Auth and App navigation stacks. Perhaps I should include the firebase onAuthStateChanged inside the useCachedResources template?
AuthenticatedUserProvider.tsx
import { useState, createContext } from 'react';
export interface IUser {
uuid: string;
email: string | null;
}
export type AuthContextType = {
user: IUser;
setUser: (newUser: IUser | null) => void;
};
export const AuthenticatedUserContext = createContext<AuthContextType | null>(null);
export const AuthenticatedUserProvider = ({ children }: { children: React.ReactNode }) => {
const [user, setUser] = useState<IUser | null>(null);
return (
<AuthenticatedUserContext.Provider value={user ? { user, setUser } : null}>
{children}
</AuthenticatedUserContext.Provider>
);
};
navigation.ts
export default function Navigation({ colorScheme }: { colorScheme: ColorSchemeName }) {
const { user } = useContext(AuthenticatedUserContext) as AuthContextType;
return (
<NavigationContainer linking={LinkingConfiguration} theme={colorScheme === 'dark' ? DarkTheme : DefaultTheme}>
{user ? <AppStack /> : <AuthStack />}
</NavigationContainer>
);
}
useCachedResources.ts
export default function useCachedResources() {
const { user, setUser } = useContext(AuthenticatedUserContext) as AuthContextType;
const [isLoadingComplete, setLoadingComplete] = useState(false);
useEffect(() => {
async function loadResourcesAndDataAsync() {
try {
SplashScreen.preventAutoHideAsync();
await Font.loadAsync({
...FontAwesome.font,
'poppins-400': require('../assets/fonts/poppins-400.ttf'),
'poppins-700': require('../assets/fonts/poppins-700.ttf'),
'poppins-900': require('../assets/fonts/poppins-900.ttf'),
});
const unsubscribeAuthStateChanged = onAuthStateChanged(auth, (authenticatedUser) => {
authenticatedUser ? setUser({ uuid: authenticatedUser.uid, email: authenticatedUser.email }) : setUser(null);
});
return unsubscribeAuthStateChanged;
} catch (e) {
console.warn(e);
} finally {
setLoadingComplete(true);
SplashScreen.hideAsync();
}
}
loadResourcesAndDataAsync();
}, [user]);
return isLoadingComplete;
}