Search code examples
reactjstypescriptreact-functional-component

'loggedInUser' is possibly 'undefined'.ts(18048)


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 }

Solution

  • 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()  || {}