admin
9 months ago
components
1 year ago
hooks
9 months ago
admin-subscriptions.tsx
1 year ago
entity.ts
9 months ago
types.ts
9 months ago
utils.ts
9 months ago
utils.ts
65 lines
| 1 | import { useEntityRecord } from '@wordpress/core-data'; |
| 2 | import { useDispatch } from '@wordpress/data'; |
| 3 | import { store as coreStore } from '@wordpress/core-data'; |
| 4 | import apiFetch from '@wordpress/api-fetch'; |
| 5 | import { Subscription } from '@givewp/subscriptions/admin/components/types'; |
| 6 | import type { GiveSubscriptionOptions } from '@givewp/subscriptions/types'; |
| 7 | |
| 8 | declare const window: { |
| 9 | GiveSubscriptionOptions: GiveSubscriptionOptions; |
| 10 | } & Window; |
| 11 | |
| 12 | /** |
| 13 | * @since 4.8.0 |
| 14 | */ |
| 15 | export function useSubscriptionEntityRecord(subscriptionId?: number) { |
| 16 | const urlParams = new URLSearchParams(window.location.search); |
| 17 | |
| 18 | const { |
| 19 | record: subscription, |
| 20 | hasResolved, |
| 21 | isResolving, |
| 22 | save, |
| 23 | edit, |
| 24 | }: { |
| 25 | record: Subscription; |
| 26 | hasResolved: boolean; |
| 27 | isResolving: boolean; |
| 28 | save: () => any; |
| 29 | edit: (data: Subscription | Partial<Subscription>) => void; |
| 30 | } = useEntityRecord('givewp', 'subscription', subscriptionId ?? urlParams.get('id')); |
| 31 | |
| 32 | return {record: subscription, hasResolved, isResolving, save, edit}; |
| 33 | } |
| 34 | |
| 35 | /** |
| 36 | * @since 4.8.0 |
| 37 | */ |
| 38 | export function useRefreshSubscriptionInBackground() { |
| 39 | const { receiveEntityRecords, invalidateResolution } = useDispatch(coreStore); |
| 40 | |
| 41 | const refreshSubscriptionInBackground = async (subscriptionId: number) => { |
| 42 | if (!subscriptionId) return; |
| 43 | |
| 44 | try { |
| 45 | const latestSubscriptionData = await apiFetch({ |
| 46 | path: `/givewp/v3/subscriptions/${subscriptionId}`, |
| 47 | }); |
| 48 | |
| 49 | receiveEntityRecords('givewp', 'subscription', latestSubscriptionData, undefined, false); |
| 50 | } catch (error) { |
| 51 | console.error('Error refreshing subscription in background:', error); |
| 52 | invalidateResolution('getEntityRecord', ['givewp', 'subscription', subscriptionId]); |
| 53 | } |
| 54 | }; |
| 55 | |
| 56 | return refreshSubscriptionInBackground; |
| 57 | } |
| 58 | |
| 59 | /** |
| 60 | * @since 4.8.0 |
| 61 | */ |
| 62 | export function getSubscriptionOptionsWindowData(): GiveSubscriptionOptions { |
| 63 | return window.GiveSubscriptionOptions; |
| 64 | } |
| 65 |