as soon as I try to get the user.username displayed in the element I get a Render error: at line {user.username} stating that it cannot read properties of null
function Profile() {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const {userToken, signOut} = React.useContext(AuthContext);
useEffect(() => {
async function loadUser() {
const response = await fetch('http://10.0.2.2:3000/me', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
});
if (!response.ok) {
setError('Error loading profile');
}
const data = await response.json();
console.log(data);
setUser(data);
setLoading(false);
}
loadUser();
}, [userToken]);
return (
<Container>
<Text>{user.username}</Text>
<Text>{user.email}</Text>
<TochableOpacity onPress={() => signOut()}>
<ButtonText>LOGOUT</ButtonText>
</TochableOpacity>
</Container>
);
}
export default Profile;
CodePudding user response:
When your component renders, you don't have a user
yet. The request is async, so you should expect an empty user in your template. If you only want to show the <Container>
if there is a user, try returning null
until you have it.
if (!user) {
return null;
}
return (
<Container>
...
</Container>
);
}
Or alternatively, use optional chaining, something like this:
<Text>{user?.username}</Text>
<Text>{user?.email}</Text>
CodePudding user response:
You initialize it with null
const [user, setUser] = useState(null);
and then do user.username
and user.email
, so naturally it errors.
The useEffect
runs after the render, and the loadUser
is async, so until that returns it will remain null.
Either show something else while loading
is true
or initialize it to {}
so that it does not crash.
const [user, setUser] = useState({});
CodePudding user response:
Posting my own solution that works!!! and THanks to Gabriele Petrioli and maten for trying to help out so quickly! The solution was that I copy pasted from another component and I hadn't switch to 'GET' method instead of 'POST' and the token: userToken wasn't set in the header.
useEffect(() => {
async function loadUser() {
const response = await fetch('http://10.0.2.2:3000/me', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
token: userToken,