-
Notifications
You must be signed in to change notification settings - Fork 290
feat: add useAuth0Suspense hook for handling auth loading state with React 19+ #1184
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
gyaneshgouraw-okta
wants to merge
3
commits into
main
Choose a base branch
from
auth0-suspense
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
7eeb79a
feat: add useAuth0Suspense hook for handling auth loading state with …
gyaneshgouraw-okta acc9ba4
Merge branch 'main' into auth0-suspense
gyaneshgouraw-okta 44b10e2
refactor: use namespace React import and retain error in useAuth0Susp…
gyaneshgouraw-okta File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,154 @@ | ||
| import { Auth0Client } from '@auth0/auth0-spa-js'; | ||
| import '@testing-library/jest-dom'; | ||
| import { | ||
| act, | ||
| render, | ||
| renderHook, | ||
| screen, | ||
| waitFor, | ||
| } from '@testing-library/react'; | ||
| import React, { Component, ReactNode, Suspense } from 'react'; | ||
| import { Auth0Provider } from '../src'; | ||
| import useAuth0Suspense from '../src/use-auth0-suspense'; | ||
| import { defer } from './helpers'; | ||
|
|
||
| const clientMock = jest.mocked(new Auth0Client({ clientId: '', domain: '' })); | ||
|
|
||
| class ErrorBoundary extends Component< | ||
| { children: ReactNode }, | ||
| { error: Error | null } | ||
| > { | ||
| state = { error: null as Error | null }; | ||
| static getDerivedStateFromError(error: Error) { | ||
| return { error }; | ||
| } | ||
| render() { | ||
| return this.state.error ? ( | ||
| <div>boundary: {this.state.error.message}</div> | ||
| ) : ( | ||
| this.props.children | ||
| ); | ||
| } | ||
| } | ||
|
|
||
| function Greeting() { | ||
| const { user, isAuthenticated } = useAuth0Suspense(); | ||
| return <div>{isAuthenticated ? `Hello ${user?.name}` : 'Please log in'}</div>; | ||
| } | ||
|
|
||
| const renderWithProvider = async (child: ReactNode) => | ||
| act(async () => { | ||
| render( | ||
| <Auth0Provider clientId="__test_client_id__" domain="__test_domain__"> | ||
| <ErrorBoundary> | ||
| <Suspense fallback={<div>loading</div>}>{child}</Suspense> | ||
| </ErrorBoundary> | ||
| </Auth0Provider> | ||
| ); | ||
| }); | ||
|
|
||
| describe('useAuth0Suspense', () => { | ||
| afterEach(() => { | ||
| window.history.pushState({}, document.title, '/'); | ||
| }); | ||
|
|
||
| it('shows the Suspense fallback while init is pending, then the content', async () => { | ||
| const userDefer = defer<{ name: string }>(); | ||
| clientMock.checkSession.mockResolvedValue(undefined); | ||
| clientMock.getUser.mockReturnValue(userDefer.promise as never); | ||
|
|
||
| await renderWithProvider(<Greeting />); | ||
|
|
||
| // Still initializing -> fallback | ||
| expect(screen.getByText('loading')).toBeInTheDocument(); | ||
|
|
||
| userDefer.resolve({ name: 'Bob' }); | ||
|
|
||
| await waitFor(() => | ||
| expect(screen.getByText('Hello Bob')).toBeInTheDocument() | ||
| ); | ||
| }); | ||
|
|
||
| it('throws init errors to the nearest Error Boundary', async () => { | ||
| clientMock.checkSession.mockRejectedValueOnce({ | ||
| error: '__test_error__', | ||
| error_description: '__test_error_description__', | ||
| }); | ||
|
|
||
| await renderWithProvider(<Greeting />); | ||
|
|
||
| await waitFor(() => | ||
| expect( | ||
| screen.getByText(/boundary: .*__test_error_description__/) | ||
| ).toBeInTheDocument() | ||
| ); | ||
| }); | ||
|
|
||
| it('throws redirect-callback init errors to the nearest Error Boundary', async () => { | ||
| // Presence of code/state in the URL makes hasAuthParams() true, so init | ||
| // takes the handleRedirectCallback branch instead of checkSession. | ||
| window.history.pushState( | ||
| {}, | ||
| document.title, | ||
| '/?code=__test_code__&state=__test_state__' | ||
| ); | ||
| clientMock.handleRedirectCallback.mockRejectedValueOnce({ | ||
| error: '__redirect_error__', | ||
| error_description: '__redirect_error_description__', | ||
| }); | ||
|
|
||
| await renderWithProvider(<Greeting />); | ||
|
|
||
| await waitFor(() => | ||
| expect( | ||
| screen.getByText(/boundary: .*__redirect_error_description__/) | ||
| ).toBeInTheDocument() | ||
| ); | ||
| }); | ||
|
|
||
| it('returns the auth methods, omitting isLoading and _initPromise', async () => { | ||
| clientMock.checkSession.mockResolvedValue(undefined); | ||
| clientMock.getUser.mockResolvedValue({ name: 'Bob' }); | ||
|
|
||
| let captured: Record<string, unknown> | undefined; | ||
| function Capture() { | ||
| captured = useAuth0Suspense() as unknown as Record<string, unknown>; | ||
| return <div>captured</div>; | ||
| } | ||
|
|
||
| await renderWithProvider(<Capture />); | ||
| await waitFor(() => | ||
| expect(screen.getByText('captured')).toBeInTheDocument() | ||
| ); | ||
|
|
||
| expect(captured).not.toHaveProperty('isLoading'); | ||
| expect(captured).not.toHaveProperty('_initPromise'); | ||
| expect(captured).toHaveProperty('error'); | ||
| expect(typeof captured!.loginWithRedirect).toBe('function'); | ||
| }); | ||
|
|
||
| it('throws a clear error when used outside an Auth0Provider', () => { | ||
| expect(() => renderHook(() => useAuth0Suspense())).toThrowError( | ||
| /must be used within/ | ||
| ); | ||
| }); | ||
|
|
||
| it('throws a clear error when React.use is unavailable', async () => { | ||
| jest.resetModules(); | ||
| jest.doMock('react', () => { | ||
| const actual = jest.requireActual('react'); | ||
| return { ...actual, use: undefined }; | ||
| }); | ||
| const { default: hook } = await import('../src/use-auth0-suspense'); | ||
| expect(() => hook()).toThrowError(/requires React 19/); | ||
| jest.dontMock('react'); | ||
| jest.resetModules(); | ||
| }); | ||
| }); | ||
|
|
||
| describe('useAuth0Suspense exports', () => { | ||
| it('is exported from the package root', async () => { | ||
| const pkg = await import('../src'); | ||
| expect(typeof pkg.useAuth0Suspense).toBe('function'); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,62 @@ | ||
| // Namespace import: `use` only exists as a named export from React 19, so | ||
| // `import { use }` fails at link time for React 16-18 consumers even if they | ||
| // never call this hook. Property access stays late-bound. | ||
| import * as React from 'react'; | ||
| import { User } from '@auth0/auth0-spa-js'; | ||
| import Auth0Context, { Auth0ContextInterface } from './auth0-context'; | ||
|
|
||
| /** | ||
| * The value returned by `useAuth0Suspense`: the full `useAuth0` interface minus | ||
| * `isLoading` and the internal `_initPromise`. `error` is | ||
| * retained for post-init failures such as `loginWithPopup`. | ||
| */ | ||
| export type Auth0SuspenseContextInterface<TUser extends User = User> = Omit< | ||
| Auth0ContextInterface<TUser>, | ||
| 'isLoading' | '_initPromise' | ||
| >; | ||
|
|
||
| /** | ||
| * ```jsx | ||
| * <Suspense fallback={<Spinner />}> | ||
| * <Profile /> | ||
| * </Suspense> | ||
| * | ||
| * function Profile() { | ||
| * const { user, isAuthenticated } = useAuth0Suspense(); | ||
| * return isAuthenticated ? <p>Hello {user.name}</p> : <p>Please log in</p>; | ||
| * } | ||
| * ``` | ||
| * | ||
| * Suspense-enabled variant of `useAuth0`. Suspends the component until Auth0 | ||
| * initialization completes (letting the nearest `<Suspense>` fallback render), | ||
| * and throws initialization errors so the nearest Error Boundary can handle | ||
| * them. Requires React 19 or later. | ||
| * | ||
| * TUser is an optional type param to provide a type to the `user` field. | ||
| */ | ||
| const useAuth0Suspense = <TUser extends User = User>( | ||
| context = Auth0Context | ||
| ): Auth0SuspenseContextInterface<TUser> => { | ||
| if (typeof React.use !== 'function') { | ||
| throw new Error( | ||
| 'useAuth0Suspense requires React 19 or later (React.use is unavailable).' | ||
| ); | ||
| } | ||
|
|
||
| const ctx = React.useContext(context) as Auth0ContextInterface<TUser>; | ||
|
|
||
| if (!ctx._initPromise) { | ||
| throw new Error( | ||
| 'useAuth0Suspense must be used within an <Auth0Provider>.' | ||
| ); | ||
| } | ||
|
|
||
| // Suspends until the init promise resolves; re-throws if it rejected. | ||
| React.use(ctx._initPromise); | ||
|
|
||
| // eslint-disable-next-line @typescript-eslint/no-unused-vars | ||
| const { isLoading, _initPromise, ...rest } = ctx; | ||
| return rest; | ||
| }; | ||
|
|
||
| export default useAuth0Suspense; | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.