index.tsx
50 lines
| 1 | import {__} from '@wordpress/i18n'; |
| 2 | import {useFormContext, useFormState} from 'react-hook-form'; |
| 3 | import {SelectOption} from '@givewp/admin/types'; |
| 4 | import useDonorAsyncSelectOptions from './useDonorAsyncSelectOptions'; |
| 5 | import AsyncSelectOption from '@givewp/admin/fields/AsyncSelectOption'; |
| 6 | |
| 7 | type AssociatedDonorProps = { |
| 8 | name: string; |
| 9 | mode: 'test' | 'live'; |
| 10 | label: string; |
| 11 | description: string; |
| 12 | } |
| 13 | |
| 14 | /** |
| 15 | * @since 4.11.0 use AsyncSelectOption |
| 16 | * @since 4.9.0 Add error prop to all AdminSectionField components |
| 17 | * @since 4.8.0 updated to async donor dropdown |
| 18 | * @since 4.6.0 |
| 19 | */ |
| 20 | export default function AssociatedDonor({name, mode, label, description}: AssociatedDonorProps) { |
| 21 | const {watch, setValue} = useFormContext(); |
| 22 | const {errors} = useFormState(); |
| 23 | const donorId = watch(name); |
| 24 | |
| 25 | const {selectedOption, loadOptions, mapOptionsForMenu, error} = useDonorAsyncSelectOptions(donorId, {mode}); |
| 26 | |
| 27 | const handleChange = (selectedOption: SelectOption) => { |
| 28 | setValue(name, selectedOption?.value ?? null, {shouldDirty: true}); |
| 29 | }; |
| 30 | |
| 31 | return ( |
| 32 | <AsyncSelectOption |
| 33 | name={name} |
| 34 | label={label} |
| 35 | description={description} |
| 36 | handleChange={handleChange} |
| 37 | selectedOption={selectedOption} |
| 38 | loadOptions={loadOptions} |
| 39 | mapOptionsForMenu={mapOptionsForMenu} |
| 40 | isLoadingError={error} |
| 41 | errorMessage={errors[name]?.message as string} |
| 42 | searchPlaceholder={__('Search for a donor...', 'give')} |
| 43 | loadingMessage={__('Loading donors...', 'give')} |
| 44 | loadingError={__('Error loading donors. Please try again.', 'give')} |
| 45 | ariaLabel={__('Select a donor', 'give')} |
| 46 | noOptionsMessage={__('No donors found.', 'give')} |
| 47 | /> |
| 48 | ); |
| 49 | } |
| 50 |