Skip to main content

User Context

The User Context carries all the data related to a user everywhere throughout your app so that you don't have to fetch it everytime you want to access it.

Using the context

In any pages in your front-end, you can access the current logged in user by caling the user context:

import { useUserContext } from '@/core/context'

export default function ProfilePage() {
const { user, isLoggedIn, checkRole } = useUserContext()

const userId = user?.id

return <>{checkRole('admin') && <div>You are admin!</div>}</>
}

Extending the context

Let's say you are developing a SaaS and users can join different workspace to work on different projects.

You can store the current 'workspace' so that everywhere in your app you know what workspace the user is working in.

This methods is called every time a user logged in or refresh the page. In the userCoreContext, you can define all the things to want to fetch and keep throughout the app to access it easily.

  1. Open /src/core/context/internal/useUserContext.tsx and add the workspaces variable
const [workspace, setWorkspaces] = useState<Workspace>(null)
  1. Add the query to fetch the workspaces of the user logged in
const { refetch: refetchWorkspace } = Api.workspace.findMany.useQuery(
{
where: {
roles: {
some: {
userId: data?.user?.id,
},
},
},
},
{
enabled: false,
onSuccess: workspaces => {
setWorkspaces(workspaces)
},
},
)

useEffect(() => {
if (status === 'authenticated') {
refetch()
refetchWorkspace()
}
}, [status])
  1. Export the workspaces variable
return (
<UserContext.Provider
value={{
user,
refetch,
checkRole,
authenticationStatus: status,
isLoggedIn,
isLoading,
workspaces,
}}
>
{children}
</UserContext.Provider>
)

You can now access all the workspaces of the current user on all your pages:

import { useUserContext } from '@/core/context'

const { user, workspaces } = useUserContext()