Skip to content

Commit

Permalink
feat: add useSession hook
Browse files Browse the repository at this point in the history
  • Loading branch information
mszekiel authored and jonas-jonas committed Oct 21, 2024
1 parent d23bb7c commit 3d1861d
Show file tree
Hide file tree
Showing 3 changed files with 107 additions and 2 deletions.
32 changes: 31 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion packages/elements-react/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,8 @@
"lodash.merge": "4.6.2",
"react-hook-form": "7.53.0",
"react-intl": "6.7.0",
"tailwind-merge": "2.5.2"
"tailwind-merge": "2.5.2",
"zustand": "5.0.0"
},
"peerDependencies": {
"react": "18.3.1",
Expand Down
74 changes: 74 additions & 0 deletions packages/elements-react/src/hooks/useSession.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
// Copyright © 2024 Ory Corp
// SPDX-License-Identifier: Apache-2.0

import { Session } from "@ory/client-fetch"
import { useCallback, useEffect } from "react"
import { create, useStore } from "zustand"
import { subscribeWithSelector } from "zustand/middleware"
import { useOryFlow } from "../context/flow-context"
import { frontendClient } from "../util/client"

type SessionStore = {
setIsLoading: (loading: boolean) => void
setSession: (session: Session) => void
isLoading?: boolean
session?: Session
error: unknown
setError: (error: unknown) => void
}

const sessionStore = create<SessionStore>()(
subscribeWithSelector((set) => ({
isLoading: false,
setIsLoading: (isLoading: boolean) => set({ isLoading }),
session: undefined,
setSession: (session: Session) => set({ session }),
error: undefined,
setError: (error: unknown) => set({ error }),
})),
)

/**
* A hook to get the current session from the Ory Network.
*
* Usage:
* ```ts
* const { session, error, isLoading } = useSession()
* ```
*
* @returns The current session, error and loading state.
*/
export const useSession = () => {
const { config } = useOryFlow()
const store = useStore(sessionStore)

const fetchSession = useCallback(async () => {
const { session, isLoading, setSession, setIsLoading, setError } =
sessionStore.getState()

if (!!session || isLoading) {
return
}

setIsLoading(true)

try {
const sessionData = await frontendClient(config.sdk.url).toSession()
setSession(sessionData)
} catch (e) {
setError(e instanceof Error ? e.message : "Unknown error occurred")
} finally {
setIsLoading(false)
}
}, [config.sdk.url])

useEffect(() => {
void fetchSession()
}, [fetchSession])

return {
session: store.session,
error: store.error,
isLoading: store.isLoading,
}
}

0 comments on commit 3d1861d

Please sign in to comment.