1

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": "maria@mail.com",
    "user_type": "vendor",
    "vendor_address": "55 bola way road",
    "vendor_fullname": "maria smith",
  },
}

Thanks for the help

delle
  • 213
  • 3
  • 15
  • Mabye the user is initially undefined and you need to add the "?" in front of name and email like so: user?.name user?.email – Maximilian Dietel Apr 04 '22 at 13:31
  • Hi, thank for your response, I change it to `{user?.name}` and `{user?.email}` but I am still getting `undefined` – delle Apr 04 '22 at 13:49
  • Please edit your post to show where you console.log the user and what the console.log looks like – Maximilian Dietel Apr 04 '22 at 13:52
  • @delle where in your code do you actually set a user? Here `const [user, setUser] = useState();` you initialize it as `undefined`, and I don't see that you ever change that. – Thomas Apr 04 '22 at 13:54
  • @MaximilianDietel I have edit my code, u can check the console.log result above – delle Apr 04 '22 at 14:07
  • @Thomas set it in login.js and as a variable in App.js see the above edited code – delle Apr 04 '22 at 14:14

1 Answers1

1

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

Zein
  • 571
  • 4
  • 24