Repository navigation
Expand file tree
/
Copy pathuseCheckout.ts
More file actions
147 lines (129 loc) · 4.49 KB
/
Copy pathuseCheckout.ts
File metadata and controls
147 lines (129 loc) · 4.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
import type {
__experimental_CheckoutCacheState,
__experimental_CheckoutInstance,
BillingCheckoutResource,
SetActiveNavigate,
} from '@clerk/types';
import { useMemo, useSyncExternalStore } from 'react';
import type { ClerkAPIResponseError } from '../../error';
import type { __experimental_CheckoutProvider } from '../contexts';
import { useCheckoutContext } from '../contexts';
import { useClerk } from './useClerk';
import { useOrganization } from './useOrganization';
import { useUser } from './useUser';
/**
* Utility type that removes function properties from a type.
*/
type RemoveFunctions<T> = {
[K in keyof T as T[K] extends (...args: any[]) => any ? never : K]: T[K];
};
/**
* Utility type that makes all properties `null`.
*/
type ForceNull<T> = {
[K in keyof T]: null;
};
type CheckoutProperties = Omit<RemoveFunctions<BillingCheckoutResource>, 'pathRoot' | 'status'>;
type FetchStatusAndError =
| {
error: ClerkAPIResponseError;
fetchStatus: 'error';
}
| {
error: null;
fetchStatus: 'idle' | 'fetching';
};
/**
* @internal
* On status === 'needs_initialization', all properties are null.
* On status === 'needs_confirmation' or 'completed', all properties are defined the same as the CommerceCheckoutResource.
*/
type CheckoutPropertiesPerStatus =
| ({
status: Extract<__experimental_CheckoutCacheState['status'], 'needs_initialization'>;
} & ForceNull<CheckoutProperties>)
| ({
status: Extract<__experimental_CheckoutCacheState['status'], 'needs_confirmation' | 'completed'>;
} & CheckoutProperties);
type __experimental_UseCheckoutReturn = {
checkout: FetchStatusAndError &
CheckoutPropertiesPerStatus & {
confirm: __experimental_CheckoutInstance['confirm'];
start: __experimental_CheckoutInstance['start'];
clear: () => void;
finalize: (params?: { navigate?: SetActiveNavigate }) => void;
getState: () => __experimental_CheckoutCacheState;
isStarting: boolean;
isConfirming: boolean;
};
};
type Params = Parameters<typeof __experimental_CheckoutProvider>[0];
export const useCheckout = (options?: Params): __experimental_UseCheckoutReturn => {
const contextOptions = useCheckoutContext();
const { for: forOrganization, planId, planPeriod } = options || contextOptions;
const clerk = useClerk();
const { organization } = useOrganization();
const { isLoaded, user } = useUser();
if (!isLoaded) {
throw new Error('Clerk: Ensure that `useCheckout` is inside a component wrapped with `<ClerkLoaded />`.');
}
if (!user) {
throw new Error('Clerk: Ensure that `useCheckout` is inside a component wrapped with `<SignedIn />`.');
}
if (forOrganization === 'organization' && !organization) {
throw new Error(
'Clerk: Ensure your flow checks for an active organization. Retrieve `orgId` from `useAuth()` and confirm it is defined. For SSR, see: https://clerk.com/docs/reference/backend/types/auth-object#how-to-access-the-auth-object',
);
}
const manager = useMemo(
() => clerk.__experimental_checkout({ planId, planPeriod, for: forOrganization }),
[user.id, organization?.id, planId, planPeriod, forOrganization],
);
const managerProperties = useSyncExternalStore(
cb => manager.subscribe(cb),
() => manager.getState(),
() => manager.getState(),
);
const properties = useMemo<CheckoutProperties | ForceNull<CheckoutProperties>>(() => {
if (!managerProperties.checkout) {
return {
id: null,
externalClientSecret: null,
externalGatewayId: null,
status: null,
totals: null,
isImmediatePlanChange: null,
planPeriod: null,
plan: null,
paymentSource: null,
freeTrialEndsAt: null,
payer: null,
};
}
const {
// eslint-disable-next-line @typescript-eslint/unbound-method
reload,
confirm,
pathRoot,
// All the above need to be removed from the properties
...rest
} = managerProperties.checkout;
return rest;
}, [managerProperties.checkout]);
const checkout = {
...properties,
getState: manager.getState,
start: manager.start,
confirm: manager.confirm,
clear: manager.clear,
finalize: manager.finalize,
isStarting: managerProperties.isStarting,
isConfirming: managerProperties.isConfirming,
error: managerProperties.error,
status: managerProperties.status,
fetchStatus: managerProperties.fetchStatus,
};
return {
checkout,
} as __experimental_UseCheckoutReturn;
};