| 1 |
import { useAsyncSelectOptions } from "@givewp/admin/hooks/useAsyncSelectOption"; |
| 2 |
import apiFetch from "@wordpress/api-fetch"; |
| 3 |
import { useEffect, useState } from "react"; |
| 4 |
|
| 5 |
export default function useFormAsyncSelectOptions(formId: number, campaignId: number, queryParams?: {}) { |
| 6 |
const [selectedForm, setSelectedForm] = useState<any>(null); |
| 7 |
|
| 8 |
useEffect(() => { |
| 9 |
const fetchForm = async () => { |
| 10 |
if (!formId) { |
| 11 |
return; |
| 12 |
} |
| 13 |
|
| 14 |
const form = await apiFetch<any>({ |
| 15 |
path: '/give-api/v2/admin/forms?search=' + formId + '&return=model', |
| 16 |
}); |
| 17 |
|
| 18 |
if (!form?.items.length) { |
| 19 |
setSelectedForm(null); |
| 20 |
return; |
| 21 |
} |
| 22 |
|
| 23 |
setSelectedForm(form.items[0]); |
| 24 |
}; |
| 25 |
|
| 26 |
fetchForm(); |
| 27 |
}, [formId]); |
| 28 |
|
| 29 |
return useAsyncSelectOptions({ |
| 30 |
recordId: formId || null, |
| 31 |
selectedOptionRecord: selectedForm, |
| 32 |
endpoint: '/give-api/v2/admin/forms', |
| 33 |
recordsFormatter: (records) => records.items, |
| 34 |
optionFormatter: (record) => { |
| 35 |
return { |
| 36 |
value: record.id, |
| 37 |
label: record.title, |
| 38 |
}; |
| 39 |
}, |
| 40 |
queryParams: { |
| 41 |
sortColumn: 'title', |
| 42 |
sortDirection: 'asc', |
| 43 |
return: 'model', |
| 44 |
campaignId, |
| 45 |
...queryParams, |
| 46 |
}, |
| 47 |
resetOnChange: campaignId |
| 48 |
}); |
| 49 |
} |
| 50 |
|