index.ts
9 months ago
useDonationsBySubscription.ts
9 months ago
useSubscriptionAmounts.ts
9 months ago
useSubscriptionCancel.ts
9 months ago
useSubscriptionSync.tsx
9 months ago
useSubscriptionCancel.ts
71 lines
| 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 |