useFreeAddonSubscription.js
72 lines
| 1 | import {useState, useCallback} from 'react'; |
| 2 | |
| 3 | /** |
| 4 | * Handles making a request to add a user to the Free Addon email subscription. It returns whether the request worked, |
| 5 | * failed, and the callback to trigger it all. |
| 6 | * |
| 7 | * @param {String} reason "rejected" or "subscribed" |
| 8 | * @returns {boolean} Whether the request was successful. |
| 9 | */ |
| 10 | async function markSubscriptionComplete(reason) { |
| 11 | const response = await fetch(giveFreeAddonModal.apiRoot, { |
| 12 | method: 'POST', |
| 13 | credentials: 'same-origin', |
| 14 | headers: { |
| 15 | 'Content-Type': 'application/json', |
| 16 | Accept: 'application/json', |
| 17 | 'X-WP-Nonce': giveFreeAddonModal.nonce, |
| 18 | }, |
| 19 | body: JSON.stringify({reason}), |
| 20 | }); |
| 21 | |
| 22 | return response.ok; |
| 23 | } |
| 24 | |
| 25 | export default function useFreeAddonSubscription() { |
| 26 | const [userSubscribed, setUserSubscribed] = useState(false); |
| 27 | const [hasSubmissionError, setHasSubmissionError] = useState(false); |
| 28 | |
| 29 | const handleSubscribe = useCallback( |
| 30 | /** |
| 31 | * @param {String} firstName |
| 32 | * @param {String} email |
| 33 | * @param {String} siteUrl |
| 34 | * @param {String} siteName |
| 35 | * @returns {Promise<void>} |
| 36 | */ |
| 37 | async (firstName, email, siteUrl, siteName) => { |
| 38 | try { |
| 39 | const response = await fetch('https://connect.givewp.com/activecampaign/subscribe/free-add-on', { |
| 40 | method: 'POST', |
| 41 | headers: { |
| 42 | 'Content-Type': 'application/json', |
| 43 | }, |
| 44 | body: JSON.stringify({ |
| 45 | first_name: firstName, |
| 46 | email, |
| 47 | website_url: siteUrl, |
| 48 | website_name: siteName, |
| 49 | }), |
| 50 | }); |
| 51 | |
| 52 | if (response.ok) { |
| 53 | setUserSubscribed(true); |
| 54 | markSubscriptionComplete('subscribed'); |
| 55 | } else { |
| 56 | setHasSubmissionError(true); |
| 57 | } |
| 58 | } catch (error) { |
| 59 | setHasSubmissionError(true); |
| 60 | } |
| 61 | }, |
| 62 | [setUserSubscribed, setHasSubmissionError] |
| 63 | ); |
| 64 | |
| 65 | return { |
| 66 | userSubscribed, |
| 67 | hasSubscriptionError: hasSubmissionError, |
| 68 | subscribeUser: handleSubscribe, |
| 69 | rejectOffer: () => markSubscriptionComplete('rejected'), |
| 70 | }; |
| 71 | } |
| 72 |