Issue
For firebase auth operations, I set up the AuthProvider.js structure whose codes I shared and tried to use it in Router.js, but I am getting this error. how can i fix it? I guess 'import React, {useState,useEffect, useContext} from 'react';' i am getting an error here
Error:TypeError: undefined is not an object (evaluating '_useContext.user')
My Router:
import { AuthContext } from './Pages/AuthProvider/AuthProvider';
const Router = () => {
const [isFirstLaunch,setIsFirstLaunch] = useState(null);
const {user, setUser} = useContext(AuthContext);
const {initializing,setInitializing} = useState(true);
useEffect(()=>{
AsyncStorage.getItem('alreadyLaunched').then(value=>{
if(value== null){
AsyncStorage.setItem('alreadyLaunched','true');
setIsFirstLaunch(true);
}else{
setIsFirstLaunch(false);
}
});
},[])
if(isFirstLaunch == null){
return null;
}
else if(isFirstLaunch== true){
return (
<NavigationContainer>
<Stack.Navigator
screenOptions={{
headerShown:false
}}
>
<Stack.Screen name='OnBoarding' component={OnBoardingPage}/>
<Stack.Screen name='AuthStack' component={AuthStack}/>
<Stack.Screen name='HomeStack' component={HomeStack}/>
<FlashMessage position="top" />
</Stack.Navigator>
</NavigationContainer>
);
}
else{
return(
<NavigationContainer>
<Stack.Navigator
screenOptions={{
headerShown:false
}}
>
<Stack.Screen name='AuthStack' component={AuthStack}/>
<Stack.Screen name='HomeStack' component={HomeStack}/>
</Stack.Navigator>
<FlashMessage position="top" />
</NavigationContainer>
)
}
}
My AuthProvider.js
import React, {createContext, useState} from 'react';
import auth from '@react-native-firebase/auth';
export const AuthContext = createContext();
export const AuthProvider = ({children}) => {
const [user, setUser] = useState(null);
return (
<AuthContext.Provider
value={{
user,
setUser,
login: async (email, password) => {
try {
await auth().signInWithEmailAndPassword(email, password);
} catch (e) {
console.log(e);
}
},
register: async (email, password) => {
try {
await auth().createUserWithEmailAndPassword(email, password)
} catch (e) {
console.log(e);
}
},
logout: async () => {
try {
await auth().signOut();
} catch (e) {
console.log(e);
}
},
}}>
{children}
</AuthContext.Provider>
);
};
Solution
we should use this type:
<AuthProvider>
<Router/>
</AuthProvider>
Answered By - selcukctn
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.