I am using Auth library to set current logged in user , I am able to obtain loggedInUser object in console , but when i check any conditions with loggedInUser , it says this error :
'loggedInUser' is possibly 'undefined'.ts(18048)
here's the code :
const UserList: FC = () => {
return (
<>
<KTCard>
<KTCardBody className='py-4'>
<PaginatedItems />
</KTCardBody>
</KTCard>
</>
)
}
const MainWrapper: FC = () => {
const intl = useIntl()
const { loggedInUser }= useAuth()
console.log(loggedInUser) // Here I am able to retrieve loggedInUser object details with id , name , token , role , etc .... Hence its working here.
return (
<>
{loggedInUser.role !== 'superAdmin' ? ( // Here is says 'loggedInUser' is possibly 'undefined'.ts(18048)
<>
<ErrorsPage />
</>
) : (
<>
<PageTitle breadcrumbs={[]}> Menu Items </PageTitle>
<UserList />
</>
)}
</>
)
}
export { MainWrapper }
CodePudding user response:
This happens when useAuth() returned undefined. Then we cannot destructure it.
Another scenario is useAuth() return any empty object which dont have a key/proploggedInUser. Give validation to handle this
loggedInUser && loggedInUser.role !== 'superAdmin'
or (using optional chaining)
loggedInUser?.role
and
const { loggedInUser }= useAuth() || {}
CodePudding user response:
The error is telling you that there is no guarantee for loggedInUser to be properly defined. So, even though you see it being properly defined at console.log, the initialization of
const { loggedInUser }= useAuth()
does not guarantee that loggedInUser will have a proper value. You can use loggedInUser?.role to remedy this problem.
