PluginProbe
GiveWP – Donation Plugin and Fundraising Platform / 4.10.1
GiveWP – Donation Plugin and Fundraising Platform v4.10.1
4.16.8 4.16.7.2 4.16.7.1 4.16.7 4.16.6.1 4.16.6 4.16.5.1 4.16.5 4.16.4 4.16.3 4.16.2 4.16.1 4.16.0 4.15.5 4.15.4 4.15.3 4.15.2 4.15.1 4.15.0 2.3.0 2.3.1 2.3.2 2.30.0 2.31.0 2.31.1 All 253 releases
give / src / Campaigns / Blocks / shared / hooks / useFormOptions.ts
useFormOptions.ts
70 lines 2.2 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 import { __ } from '@wordpress/i18n';
2 import { useSelect } from '@wordpress/data';
3 import type { Post } from '@wordpress/core-data/src/entity-types';
4 import type { Form } from '../../CampaignForm/resources/types';
5 import useSWR from 'swr';
6 import { addQueryArgs } from '@wordpress/url';
7 import apiFetch from '@wordpress/api-fetch';
8
9 export interface FormOption extends Form {
10 label: string;
11 value: number;
12 isLegacyTemplate: boolean;
13 }
14
15 /**
16 * @since 4.3.0
17 */
18 export default function useFormOptions(campaignId?: number): {
19 formOptions: FormOption[];
20 isResolving: boolean;
21 } {
22 const { forms, isResolving } = useSelect((select) => {
23 const query = { per_page: 100 };
24 return {
25 // @ts-ignore
26 forms: select('core').getEntityRecords<Post[]>('postType', 'give_forms', query),
27 // @ts-ignore
28 isResolving: select('core/data').getIsResolving('core', 'getEntityRecords', [
29 'postType',
30 'give_forms',
31 query,
32 ]),
33 };
34 }, []);
35
36 const { data, isLoading } = useSWR<{ items: { id: number }[] }>(
37 campaignId
38 ? addQueryArgs('/give-api/v2/admin/forms', {
39 campaignId,
40 status: 'publish',
41 }) as string
42 : null,
43 (path) => apiFetch({ path })
44 );
45
46 const campaignFormIds = data?.items?.map((form) => form.id) ?? [];
47
48 const filteredForms =
49 campaignId && campaignFormIds.length > 0
50 ? forms?.filter((form) => campaignFormIds.includes(form?.id))
51 : forms;
52
53 const formOptions: FormOption[] =
54 filteredForms?.map(({ title, id, formTemplate, isLegacyForm, link, name }) => ({
55 label: __(title?.rendered || name || 'Untitled Form', 'give'),
56 value: id,
57 isLegacyForm,
58 isLegacyTemplate: isLegacyForm && formTemplate === 'legacy',
59 link,
60 })) ?? [];
61
62 return {
63 formOptions:
64 isResolving || isLoading
65 ? [{ label: __('Loading...', 'give'), value: 0 } as FormOption]
66 : formOptions,
67 isResolving: isResolving || isLoading,
68 };
69 }
70