I am currently trying to work with Okta's React SDK to build an application using React using TypeScript, and I've chosen to use functional components instead of class-based ones.
As such, I am having an issue with rendering part of my app's menu based on the authenticated state of the user. The documentation shows using useEffect() to get the authenticated status of the user then using useState() to store user information based on that status.
That seems quite logical in practice and a great idea, but when I try to use the following component:
import React, { useState, useEffect } from 'react';
import { Dropdown } from 'semantic-ui-react';
import { useOktaAuth } from '@okta/okta-react';
export const HeaderUserMenu = () => {
// Okta Hook, State
const { authState, oktaAuth } = useOktaAuth();
const [ userInfo, setUserInfo ] = useState(null);
// Get info when our state/etc update with this.
useEffect(() => {
if (!authState.isAuthenticated) {
setUserInfo(null);
} else {
oktaAuth.token.getUserInfo()
.then((info: any) => setUserInfo(info))
}
}, [authState, oktaAuth])
return (
{ userInfo &&
<Dropdown.Menu item text={userInfo.username}>
<Dropdown.Item>Log Info</Dropdown.Item>
</Dropdown.Menu>
}
)
}
I receive two errors:
',' expected. - This is pointing to the use of the && operator to check userInfo (is it null or not?) for conditional rendering of this component.
Object is possibly 'null'. - This is pointing to the use of userInfo.username inside the conditionally rendered stuff. The whole point of the logic is to only render if userInfo isn't null, so at this point userInfo can't be null, right?
I'm not sure what I'm doing wrong here.
I get the feeling that it has something to do with useEffect, but I guess I could be wrong, I'm still sort of getting used to using hooks in React, and even though I've used useState before, I've never used effects until now.
Thanks in advance!