Home > Net >  useContext returns undefined (React Native, Expo)
useContext returns undefined (React Native, Expo)

Time:04-05

I am trying to retrieve user data(name, email) to display after I login but I keep getting undefined but whenever I console.log( user ) I see all the data including the name and email

Context.js

import React  from 'react';
const AuthContext = React.createContext();
export default AuthContext;

App.js

import AuthContext from './context';

const App = () => {
  const [user, setUser] = useState();

  return (
    <AuthContext.Provider value={{user, setUser}}>
      <NavigationContainer>
          { user ? <AppNavigator /> : <AuthNavigator/> }
      </NavigationContainer>
    </AuthContext.Provider>
  )
} 

Panel.js

const Panel = ({navigation}) => {
  const { user } = useContext(AuthContext);


  return (
    <View style={styles.container}>
      <Text>Name {user.name} </Text>
      <Text>Email {user.email} </Text>
    </View>
  )
}

Login.js

const handleSubmit = async ( { email, password } ) =>{
    const response = await axios.post(userLogin, 
    { 
        email, 
        password,
    })
    .then((response) => { 
        const user = response.data;
        authContext.setUser(user);
        // console.log(response.data);
    })
    .catch(error => { 
        console.log(error);
    }); 
}

console.log(user) result

Object {
  "token": "27|YUHmPPwmRkgQRFkAmbEpSjweXN6QI8eR7O1bHhfd",
  "user": Object {
    "id": 2,
    "name": "maria",
    "email": "[email protected]",
    "user_type": "vendor",
    "vendor_address": "55 bola way road",
    "vendor_fullname": "maria smith",
  },
}

Thanks for the help

CodePudding user response:

it might be because at first render user is undefined, so you can't access email and name you can use user?.user.?name like so for email. to validate what I'm saying try giving a static user in The App.js you will see that the error is gone

  • Related