PluginProbe
GiveWP – Donation Plugin and Fundraising Platform / 4.16.8.1
GiveWP – Donation Plugin and Fundraising Platform v4.16.8.1
4.16.9 4.16.8.1 4.16.8 4.16.7.2 4.16.7.1 4.16.7 4.16.6.1 4.16.6 4.16.5.1 4.16.5 4.16.4 4.16.3 4.16.2 4.16.1 4.16.0 4.15.5 4.15.4 4.15.3 4.15.2 4.15.1 4.15.0 2.3.0 2.3.1 2.3.2 2.30.0 All 255 releases
give / src / Subscriptions / resources / utils.ts

utils.ts in GiveWP – Donation Plugin and Fundraising Platform 4.16.8.1, at src/Subscriptions/resources/utils.ts

75 lines 2.4 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
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.11.0 added refreshSubscriptionInBackground to the save method
14 * @since 4.8.0
15 */
16 export function useSubscriptionEntityRecord(subscriptionId?: number) {
17 const urlParams = new URLSearchParams(window.location.search);
18 const refreshSubscriptionInBackground = useRefreshSubscriptionInBackground();
19
20 const {
21 record,
22 hasResolved,
23 isResolving,
24 save,
25 edit,
26 }: {
27 record: Subscription;
28 hasResolved: boolean;
29 isResolving: boolean;
30 save: () => any;
31 edit: (data: Subscription | Partial<Subscription>) => void;
32 } = useEntityRecord('givewp', 'subscription', subscriptionId ?? urlParams.get('id'));
33
34 const saveAndRefresh = async () => {
35 const response = await save();
36 await refreshSubscriptionInBackground(response?.id);
37
38 return response;
39 }
40
41 return {record, hasResolved, isResolving, save: saveAndRefresh, edit};
42 }
43
44 /**
45 * @since 4.11.0 added _embed=true to the request
46 * @since 4.8.0
47 */
48 export function useRefreshSubscriptionInBackground() {
49 const { receiveEntityRecords, invalidateResolution } = useDispatch(coreStore);
50
51 const refreshSubscriptionInBackground = async (subscriptionId: number) => {
52 if (!subscriptionId) return;
53
54 try {
55 const latestSubscriptionData = await apiFetch({
56 path: `/givewp/v3/subscriptions/${subscriptionId}?_embed=true`,
57 });
58
59 receiveEntityRecords('givewp', 'subscription', latestSubscriptionData, undefined, false);
60 } catch (error) {
61 console.error('Error refreshing subscription in background:', error);
62 invalidateResolution('getEntityRecord', ['givewp', 'subscription', subscriptionId]);
63 }
64 };
65
66 return refreshSubscriptionInBackground;
67 }
68
69 /**
70 * @since 4.8.0
71 */
72 export function getSubscriptionOptionsWindowData(): GiveSubscriptionOptions {
73 return window.GiveSubscriptionOptions;
74 }
75