useCurrencyFormatter.ts
2 years ago
useDonationSummary.ts
1 year ago
useFormData.ts
1 year ago
useFormSubmitButton.ts
1 year ago
useVisibilityCondition.ts
2 years ago
useDonationSummary.ts
47 lines
| 1 | import { |
| 2 | DonationSummaryLineItem, |
| 3 | useDonationSummaryContext, |
| 4 | useDonationSummaryDispatch |
| 5 | } from '@givewp/forms/app/store/donation-summary'; |
| 6 | import { |
| 7 | addAmountToTotal, |
| 8 | addItem, |
| 9 | removeAmountFromTotal, |
| 10 | removeItem |
| 11 | } from '@givewp/forms/app/store/donation-summary/reducer'; |
| 12 | import {useCallback} from '@wordpress/element'; |
| 13 | |
| 14 | /** |
| 15 | * The donation summary hook is used to interact with the donation summary context which wraps around our donation form. |
| 16 | * It provides methods to add and remove items from the summary, as well as to add and remove amounts from the total. |
| 17 | * It also provides the current items and totals from the context, making it easier to access form values specific to donations. |
| 18 | * |
| 19 | * @since 4.0.0 added getTotalSum |
| 20 | * @since 3.0.0 |
| 21 | */ |
| 22 | export default function useDonationSummary() { |
| 23 | const { items, totals } = useDonationSummaryContext(); |
| 24 | const dispatch = useDonationSummaryDispatch(); |
| 25 | |
| 26 | return { |
| 27 | items, |
| 28 | totals, |
| 29 | addItem: useCallback((item: DonationSummaryLineItem) => dispatch(addItem(item)), [dispatch]), |
| 30 | removeItem: useCallback((itemId: string) => dispatch(removeItem(itemId)), [dispatch]), |
| 31 | addToTotal: useCallback( |
| 32 | (itemId: string, amount: number) => dispatch(addAmountToTotal(itemId, amount)), |
| 33 | [dispatch] |
| 34 | ), |
| 35 | removeFromTotal: useCallback((itemId: string) => dispatch(removeAmountFromTotal(itemId)), [dispatch]), |
| 36 | getTotalSum: useCallback((amount: number) => |
| 37 | Number( |
| 38 | Object.values({ |
| 39 | ...totals, |
| 40 | amount |
| 41 | }).reduce((total: number, amount: number) => { |
| 42 | return total + amount; |
| 43 | }, 0) |
| 44 | ), [totals]) |
| 45 | }; |
| 46 | } |
| 47 |