-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
99 lines (84 loc) · 2.04 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import React, { ReactNode, useEffect, useState } from 'react';
import apiFetch from '@wordpress/api-fetch';
import { Notice, SelectControl, Spinner } from '@wordpress/components';
import { useSelect } from '@wordpress/data';
import { __ } from '@wordpress/i18n';
import { addQueryArgs } from '@wordpress/url';
import { createOptionsFromTerms } from '../..';
const DEFAULT_OPTION = {
label: '',
value: '',
};
const FALLBACK_OPTION = {
disabled: true,
label: __( 'No items found!', 'block-editor-components' ),
value: '',
};
/**
* A dropdown control that allows for selecting a single term in the given taxonomy.
*
* @param {object} props - Component props
* @returns {ReactNode} Component.
*/
function FetchAllTermSelectControl( props ) {
const {
defaultOption = DEFAULT_OPTION,
fallbackOption = FALLBACK_OPTION,
taxonomy,
...selectProps
} = props;
const [ error, setError ] = useState();
const [ options, setOptions ] = useState();
const basePath = useSelect(
( select ) => select( 'core' ).getTaxonomy( taxonomy )?.rest_base,
[ taxonomy ]
);
useEffect(
() => {
if ( ! basePath ) {
return;
}
( async () => {
try {
const response = await apiFetch( {
path: addQueryArgs( `/wp/v2/${ basePath }`, {
_fields: 'id,name',
context: 'view',
per_page: -1,
} ),
} );
if ( ! response?.length ) {
setOptions( fallbackOption ? [ fallbackOption ] : [] );
return;
}
setOptions( [
...( defaultOption ? [ defaultOption ] : [] ),
...createOptionsFromTerms( response ),
] );
} catch ( error ) {
setError( error.message ?? __( 'Unknown error.', 'block-editor-components' ) );
}
} )();
},
[ basePath, defaultOption, fallbackOption ]
);
if ( error ) {
return (
<Notice isDismissible={ false } status="error">
<p>{ error }</p>
</Notice>
);
}
if ( ! options ) {
return (
<Spinner />
);
}
return (
<SelectControl
{ ...selectProps }
options={ options }
/>
);
}
export default FetchAllTermSelectControl;