[Login] Read User Info and set variable

Hi all,
i would like to read user information and set “Admin” variable to yes if its custom attributes is equal to 1.
The problem is that when i want to read user attributes the program crashes with TypeError: Cannot read property ‘attributes’ of undefined"

This is my code:

async function onLoad() {
  try {
    await Auth.currentSession();
		userHasAuthenticated(true);
		await Auth.currentAuthenticatedUser().then(user => setUserData(user));
                if(userData.attributes['custom:isAdmin'] === "1" ) {setIsAdmin(true)}
  }
  catch(e) {
    if (e !== 'No current user') {
      alert(e);
    }
  }
  setIsAuthenticating(false);
}

How can i set this variable? I need to set a link in menu reserved for admin

Can we see your setUserData function? Assuming that does not have an issue, I believe your if statement after it being called is firing before the async call above is complete.

1 Like

This is the code:

    function App(props) {
	const [isAuthenticating, setIsAuthenticating] = useState(true);
	const [isAuthenticated, userHasAuthenticated] = useState(false);
	const [userData, setUserData] = useState('');
	const [isAdmin, setIsAdmin] = useState(false);

	useEffect(() => {
  onLoad();
}, []);

async function handleLogout() {
  await Auth.signOut();
  userHasAuthenticated(false);
	setIsAdmin(false);
  props.history.push("/login");
}

async function onLoad() {
  try {
    await Auth.currentSession();
		userHasAuthenticated(true);
		await Auth.currentUserInfo().then(user => setUserData(user));
		if(userData.attributes['custom:isAdmin'] === "1" ) {setIsAdmin(true)}
  }
  catch(e) {
    if (e !== 'No current user') {
      alert(e);
    }
  }
  setIsAuthenticating(false);
}

Hmm this line looks a bit weird.

await Auth.currentUserInfo().then(user => setUserData(user));
if(userData.attributes['custom:isAdmin'] === "1" ) {setIsAdmin(true)}

Remember that when you call setUserData, it’ll re-render your component and set the userData variable. This means that it won’t be set right away. So it’ll be null right after setUserData is called. So the next line would fail.

Also, remember that since you are using async/await, you shouldn’t have to do the .then().