Skip to content

Commit

Permalink
chore(clerk-react): Improve JSDoc comments (#5053)
Browse files Browse the repository at this point in the history
  • Loading branch information
LekoArts authored Jan 31, 2025
1 parent 0f95982 commit 833693a
Show file tree
Hide file tree
Showing 23 changed files with 828 additions and 106 deletions.
8 changes: 8 additions & 0 deletions .changeset/witty-ladybugs-fix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
'@clerk/nextjs': patch
'@clerk/shared': patch
'@clerk/clerk-react': patch
'@clerk/types': patch
---

Improve JSDoc comments to provide better IntelliSense in your IDE
4 changes: 1 addition & 3 deletions packages/nextjs/src/app-router/server/currentUser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,7 @@ import { auth } from './auth';
* - counts towards the [Backend API request rate limit](https://clerk.com/docs/backend-requests/resources/rate-limits#rate-limits).
*
* @example
* ```tsx
* // app/page.tsx
*
* ```tsx {{ filename: 'app/page.tsx' }}
* import { currentUser } from '@clerk/nextjs/server'
*
* export default async function Page() {
Expand Down
12 changes: 4 additions & 8 deletions packages/nextjs/src/server/buildClerkProps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,9 @@ type BuildClerkProps = (req: RequestLike, authState?: BuildClerkPropsInitState)
* Clerk uses `buildClerkProps` to inform the client-side helpers of the authentication state of the user. This function is used SSR in the `getServerSideProps` function of your Next.js application.
*
* @example
* **Basic usage**
*
* ```tsx
* // pages/myServerSidePage.tsx
* ### Basic usage
*
* ```tsx {{ filename: 'pages/myServerSidePage.tsx' }}
* import { getAuth, buildClerkProps } from '@clerk/nextjs/server'
* import { GetServerSideProps } from 'next'
*
Expand All @@ -33,13 +31,11 @@ type BuildClerkProps = (req: RequestLike, authState?: BuildClerkPropsInitState)
* ```
*
* @example
* **Usage with `clerkClient`**
* ### Usage with `clerkClient`
*
* The `clerkClient` allows you to access the Clerk API. You can use this to retrieve or update data.
*
* ```tsx
* // pages/api/example.ts
*
* ```tsx {{ filename: 'pages/api/example.ts' }}
* import { getAuth, buildClerkProps, clerkClient } from '@clerk/nextjs/server'
* import { GetServerSideProps } from 'next'
*
Expand Down
17 changes: 6 additions & 11 deletions packages/nextjs/src/server/createGetAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,12 +84,11 @@ export const createSyncGetAuth = ({
* @returns The `Auth` object. See the [Auth reference](https://clerk.com/docs/references/backend/types/auth-object) for more information.
*
* @example
* **Protect API routes**
* ### Protect API routes
*
* The following example demonstrates how to protect an API route by checking if the `userId` is present in the `getAuth()` response.
*
* ```tsx
* // app/api/example/route.ts
* ```tsx {{ filename: 'app/api/example/route.ts' }}
* import { getAuth } from '@clerk/nextjs/server'
* import type { NextApiRequest, NextApiResponse } from 'next'
*
Expand All @@ -107,13 +106,11 @@ export const createSyncGetAuth = ({
* ```
*
* @example
* **Usage with `getToken()`**
* ### Usage with `getToken()`
*
* `getAuth()` returns [`getToken()`](https://clerk.com/docs/references/backend/types/auth-object#get-token), which is a method that returns the current user's session token or a custom JWT template.
*
* ```tsx
* // app/api/example/route.ts
*
* ```tsx {{ filename: 'app/api/example/route.ts' }}
* import { getAuth } from '@clerk/nextjs/server'
* import type { NextApiRequest, NextApiResponse } from 'next'
*
Expand All @@ -130,13 +127,11 @@ export const createSyncGetAuth = ({
* ```
*
* @example
* **Usage with `clerkClient`**
* ### Usage with `clerkClient`
*
* `clerkClient` is used to access the [Backend SDK](https://clerk.com/docs/references/backend/overview), which exposes Clerk's Backend API resources. You can use `getAuth()` to pass authentication information that many of the Backend SDK methods require, like the user's ID.
*
* ```tsx
* // app/api/example/route.ts
*
* ```tsx {{ filename: 'app/api/example/route.ts' }}
* import { clerkClient, getAuth } from '@clerk/nextjs/server'
* import type { NextApiRequest, NextApiResponse } from 'next'
*
Expand Down
12 changes: 6 additions & 6 deletions packages/react/src/hooks/__tests__/useRoutingProps.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ describe('useRoutingProps()', () => {
});

test('defaults to path routing and a path prop is required', () => {
const TestingComponent = props => {
const TestingComponent = (props: any) => {
const options = useRoutingProps('TestingComponent', props);
return <div>{JSON.stringify(options)}</div>;
};
Expand All @@ -27,7 +27,7 @@ describe('useRoutingProps()', () => {
});

test('the path option is ignored when "hash" routing prop', () => {
const TestingComponent = props => {
const TestingComponent = (props: any) => {
const options = useRoutingProps('TestingComponent', props, { path: '/path-option' });
return <div>{JSON.stringify(options)}</div>;
};
Expand All @@ -43,7 +43,7 @@ describe('useRoutingProps()', () => {
});

test('the path option is ignored when "virtual" routing prop', () => {
const TestingComponent = props => {
const TestingComponent = (props: any) => {
const options = useRoutingProps('TestingComponent', props, { path: '/path-option' });
return <div>{JSON.stringify(options)}</div>;
};
Expand All @@ -59,7 +59,7 @@ describe('useRoutingProps()', () => {
});

test('throws error when "hash" routing and path prop are set', () => {
const TestingComponent = props => {
const TestingComponent = (props: any) => {
const options = useRoutingProps('TestingComponent', props);
return <div>{JSON.stringify(options)}</div>;
};
Expand All @@ -77,7 +77,7 @@ describe('useRoutingProps()', () => {
});

test('throws error when "virtual" routing and path prop are set', () => {
const TestingComponent = props => {
const TestingComponent = (props: any) => {
const options = useRoutingProps('TestingComponent', props);
return <div>{JSON.stringify(options)}</div>;
};
Expand All @@ -95,7 +95,7 @@ describe('useRoutingProps()', () => {
});

test('path prop has priority over path option', () => {
const TestingComponent = props => {
const TestingComponent = (props: any) => {
const options = useRoutingProps('TestingComponent', props, { path: '/path-option' });
return <div>{JSON.stringify(options)}</div>;
};
Expand Down
56 changes: 38 additions & 18 deletions packages/react/src/hooks/useAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,32 +9,52 @@ import { invalidStateError } from '../errors/messages';
import { useAssertWrappedByClerkProvider } from './useAssertWrappedByClerkProvider';
import { createGetToken, createSignOut } from './utils';

type UseAuth = (initialAuthState?: any) => UseAuthReturn;

/**
* Returns the current auth state, the user and session ids and the `getToken`
* that can be used to retrieve the given template or the default Clerk token.
* The `useAuth()` hook provides access to the current user's authentication state and methods to manage the active session.
*
* Until Clerk loads, `isLoaded` will be set to `false`.
* Once Clerk loads, `isLoaded` will be set to `true`, and you can
* safely access the `userId` and `sessionId` variables.
* @example
*
* For projects using NextJs or Remix, you can have immediate access to this data during SSR
* simply by using the `ClerkProvider`.
* The following example demonstrates how to use the `useAuth()` hook to access the current auth state, like whether the user is signed in or not. It also includes a basic example for using the `getToken()` method to retrieve a session token for fetching data from an external resource.
*
* @example
* ```tsx {{ filename: 'src/pages/ExternalDataPage.tsx' }}
* import { useAuth } from '@clerk/clerk-react'
*
* function Hello() {
* const { isSignedIn, sessionId, userId } = useAuth();
* if(isSignedIn) {
* return null;
* export default function ExternalDataPage() {
* const { userId, sessionId, getToken, isLoaded, isSignedIn } = useAuth()
*
* const fetchExternalData = async () => {
* const token = await getToken()
*
* // Fetch data from an external API
* const response = await fetch('https://api.example.com/data', {
* headers: {
* Authorization: `Bearer ${token}`,
* },
* })
*
* return response.json()
* }
* console.log(sessionId, userId)
* return <div>...</div>
*
* if (!isLoaded) {
* return <div>Loading...</div>
* }
*
* if (!isSignedIn) {
* return <div>Sign in to view this page</div>
* }
*
* return (
* <div>
* <p>
* Hello, {userId}! Your current active session is {sessionId}.
* </p>
* <button onClick={fetchExternalData}>Fetch Data</button>
* </div>
* )
* }
* ```
*/
export const useAuth: UseAuth = (initialAuthState = {}) => {
export const useAuth = (initialAuthState: any = {}): UseAuthReturn => {
useAssertWrappedByClerkProvider('useAuth');

const authContextFromHook = useAuthContext();
Expand Down Expand Up @@ -77,7 +97,7 @@ export const useAuth: UseAuth = (initialAuthState = {}) => {
* session and user identifiers, organization roles, and a `has` function for authorization checks.
* Additionally, it provides `signOut` and `getToken` functions if applicable.
*
* Example usage:
* @example
* ```tsx
* const {
* isLoaded,
Expand Down
35 changes: 32 additions & 3 deletions packages/react/src/hooks/useSignIn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,38 @@ import type { UseSignInReturn } from '@clerk/types';
import { useIsomorphicClerkContext } from '../contexts/IsomorphicClerkContext';
import { useAssertWrappedByClerkProvider } from './useAssertWrappedByClerkProvider';

type UseSignIn = () => UseSignInReturn;

export const useSignIn: UseSignIn = () => {
/**
* The `useSignIn()` hook provides access to the [`SignIn`](https://clerk.com/docs/references/javascript/sign-in/sign-in) object, which allows you to check the current state of a sign-in attempt and manage the sign-in flow. You can use this to create a [custom sign-in flow](https://clerk.com/docs/custom-flows/overview#sign-in-flow).
*
* @example
* ### Check the current state of a sign-in
*
* The following example uses the `useSignIn()` hook to access the [`SignIn`](https://clerk.com/docs/references/javascript/sign-in/sign-in) object, which contains the current sign-in attempt status and methods to create a new sign-in attempt. The `isLoaded` property is used to handle the loading state.
*
* ```tsx {{ filename: 'src/pages/SignInPage.tsx' }}
* import { useSignIn } from '@clerk/clerk-react'
*
* export default function SignInPage() {
* const { isLoaded, signIn } = useSignIn()
*
* if (!isLoaded) {
* // Handle loading state
* return null
* }
*
* return <div>The current sign-in attempt status is {signIn?.status}.</div>
* }
* ```
*
* @example
* ### Create a custom sign-in flow with `useSignIn()`
*
* The `useSignIn()` hook can also be used to build fully custom sign-in flows, if Clerk's prebuilt components don't meet your specific needs or if you require more control over the authentication flow. Different sign-in flows include email and password, email and phone codes, email links, and multifactor (MFA). To learn more about using the `useSignIn()` hook to create custom flows, see the [custom flow guides](https://clerk.com/docs/custom-flows/overview).
*
* ```
* ```
*/
export const useSignIn = (): UseSignInReturn => {
useAssertWrappedByClerkProvider('useSignIn');

const isomorphicClerk = useIsomorphicClerkContext();
Expand Down
35 changes: 32 additions & 3 deletions packages/react/src/hooks/useSignUp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,38 @@ import type { UseSignUpReturn } from '@clerk/types';
import { useIsomorphicClerkContext } from '../contexts/IsomorphicClerkContext';
import { useAssertWrappedByClerkProvider } from './useAssertWrappedByClerkProvider';

type UseSignUp = () => UseSignUpReturn;

export const useSignUp: UseSignUp = () => {
/**
* The `useSignUp()` hook provides access to the [`SignUp`](https://clerk.com/docs/references/javascript/sign-up/sign-up) object, which allows you to check the current state of a sign-up attempt and manage the sign-up flow. You can use this to create a [custom sign-up flow](https://clerk.com/docs/custom-flows/overview#sign-up-flow).
*
* @example
* ### Check the current state of a sign-up
*
* The following example uses the `useSignUp()` hook to access the [`SignUp`](https://clerk.com/docs/references/javascript/sign-up/sign-up) object, which contains the current sign-up attempt status and methods to create a new sign-up attempt. The `isLoaded` property is used to handle the loading state.
*
* ```tsx {{ filename: 'src/pages/SignUpPage.tsx' }}
* import { useSignUp } from '@clerk/clerk-react'
*
* export default function SignUpPage() {
* const { isLoaded, signUp } = useSignUp()
*
* if (!isLoaded) {
* // Handle loading state
* return null
* }
*
* return <div>The current sign-up attempt status is {signUp?.status}.</div>
* }
* ```
*
* @example
* ### Create a custom sign-up flow with `useSignUp()`
*
* The `useSignUp()` hook can also be used to build fully custom sign-up flows, if Clerk's prebuilt components don't meet your specific needs or if you require more control over the authentication flow. Different sign-up flows include email and password, email and phone codes, email links, and multifactor (MFA). To learn more about using the `useSignUp()` hook to create custom flows, see the [custom flow guides](https://clerk.com/docs/custom-flows/overview).
*
* ```tsx
* ```
*/
export const useSignUp = (): UseSignUpReturn => {
useAssertWrappedByClerkProvider('useSignUp');

const isomorphicClerk = useIsomorphicClerkContext();
Expand Down
2 changes: 1 addition & 1 deletion packages/react/src/isomorphicClerk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1151,7 +1151,7 @@ export class IsomorphicClerk implements IsomorphicLoadedClerk {
}
};

authenticateWithOKXWallet = async (params: AuthenticateWithOKXWalletParams): Promise<void> => {
authenticateWithOKXWallet = async (params?: AuthenticateWithOKXWalletParams): Promise<void> => {
const callback = () => this.clerkjs?.authenticateWithOKXWallet(params);
if (this.clerkjs && this.#loaded) {
return callback() as Promise<void>;
Expand Down
4 changes: 4 additions & 0 deletions packages/react/typedoc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"$schema": "https://typedoc.org/schema.json",
"entryPoints": ["./src/hooks/index.ts"]
}
22 changes: 22 additions & 0 deletions packages/shared/src/react/hooks/useClerk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,28 @@ import type { LoadedClerk } from '@clerk/types';

import { useAssertWrappedByClerkProvider, useClerkInstanceContext } from '../contexts';

/**
* The `useClerk()` hook provides access to the [`Clerk`](https://clerk.com/docs/references/javascript/clerk/clerk) object, allowing you to build alternatives to any Clerk Component.
*
* @warning
* This composable should only be used for advanced use cases, such as building a completely custom OAuth flow or as an escape hatch to access to the `Clerk` object.
*
* @returns The `Clerk` object, which includes all the methods and properties listed in the [`Clerk` reference](https://clerk.com/docs/references/javascript/clerk/clerk).
*
* @example
*
* The following example uses the `useClerk()` hook to access the `clerk` object. The `clerk` object is used to call the [`openSignIn()`](https://clerk.com/docs/references/javascript/clerk/clerk#sign-in) method to open the sign-in modal.
*
* ```tsx {{ filename: 'src/Home.tsx' }}
* import { useClerk } from '@clerk/clerk-react'
*
* export default function Home() {
* const clerk = useClerk()
*
* return <button onClick={() => clerk.openSignIn({})}>Sign in</button>
* }
* ```
*/
export const useClerk = (): LoadedClerk => {
useAssertWrappedByClerkProvider('useClerk');
return useClerkInstanceContext();
Expand Down
Loading

0 comments on commit 833693a

Please sign in to comment.