PluginProbe
GiveWP – Donation Plugin and Fundraising Platform / 4.16.9
GiveWP – Donation Plugin and Fundraising Platform v4.16.9
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 / hooks / useSubscriptionCancel.ts

useSubscriptionCancel.ts in GiveWP – Donation Plugin and Fundraising Platform 4.16.9, at src/Subscriptions/resources/hooks/useSubscriptionCancel.ts

71 lines 2.3 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 import apiFetch from '@wordpress/api-fetch';
2 import { useDispatch } from '@wordpress/data';
3 import { __ } from '@wordpress/i18n';
4 import { useState } from 'react';
5 import { Subscription } from '../admin/components/types';
6
7 /**
8 * @since 4.8.0
9 */
10 const isResponseSubscription = (response: unknown): response is Subscription => {
11 return typeof response === 'object' && response !== null && 'id' in response;
12 };
13
14 /**
15 * @since 4.8.0
16 */
17 export default function useSubscriptionCancel(subscription: Subscription) {
18 const [isCancelling, setIsCancelling] = useState(false);
19 const [isCancelled, setIsCancelled] = useState(false);
20 const dispatch = useDispatch('givewp/admin-details-page-notifications');
21 const {invalidateResolution, invalidateResolutionForStore} = useDispatch('core');
22
23 const invalidateSubscriptionCache = () => {
24 invalidateResolution('getEntityRecords', ['givewp', 'subscription']);
25 invalidateResolutionForStore();
26 };
27
28 const cancel = async (trash: boolean = false) => {
29 setIsCancelling(true);
30 const response = await apiFetch({path: `/givewp/v3/subscriptions/${subscription.id}/cancel`, method: 'POST', data: {trash}});
31
32 if (isResponseSubscription(response) && response.status === 'cancelled') {
33 setIsCancelling(false);
34 setIsCancelled(true);
35
36 invalidateSubscriptionCache();
37
38 if (trash) {
39 dispatch.addSnackbarNotice({
40 id: 'cancel-subscription',
41 content: __('Subscription cancelled and moved to trash', 'give'),
42 });
43 } else {
44 dispatch.addSnackbarNotice({
45 id: 'cancel-subscription',
46 content: __('Subscription cancelled successfully', 'give'),
47 });
48 }
49
50 return response;
51 } else {
52 console.error('Failed to cancel subscription', response);
53 setIsCancelling(false);
54 setIsCancelled(false);
55
56 dispatch.addSnackbarNotice({
57 id: 'cancel-subscription',
58 content: __('Failed to cancel subscription', 'give'),
59 });
60
61 throw new Error('Failed to cancel subscription');
62 }
63 };
64
65 return {
66 isCancelling,
67 cancel,
68 isCancelled,
69 };
70 }
71