User Context
The User Context is a crucial part of the application that provides access to user-related information throughout the app. It uses React's Context API to make user data and authentication status available to all components without prop drilling.
Key Features
- Authentication Status: Tracks whether the user is logged in, loading, or unauthenticated.
- User Data: Provides access to the current user's information.
- Role Checking: Allows checking if the user has a specific role.
- Organization Support: If the organization module is active, it provides additional organization-related data.
Usage
To use the User Context in your components:
import { useUserContext } from '@/core/context'
function MyComponent() {
const { user, isLoggedIn, checkRole, authenticationStatus } = useUserContext()
if (authenticationStatus === 'loading') {
return <div>Loading...</div>
}
if (!isLoggedIn) {
return <div>Please log in</div>
}
return (
<div>
<h1>Welcome, {user.name}!</h1>
{checkRole('admin') && <AdminPanel />}
</div>
)
}
Available Properties
user
: The current user object (if logged in)isLoggedIn
: Boolean indicating if the user is authenticatedcheckRole
: Function to check if the user has a specific roleauthenticationStatus
: Current authentication status ('unauthenticated', 'loading', or 'authenticated')isLoading
: Boolean indicating if user data is still loadingrefetch
: Function to manually refetch user data
When the organization module is active, additional properties are available:
organization
: Current organization dataorganizationRoles
: User's roles in the current organizationorganizations
: All organizations associated with the usercheckOrganizationRole
: Function to check user's role in the current organization