Get terms by taxonomy for select control option groups

Copied
import { __ } from "@wordpress/i18n"; import { InspectorControls } from "@wordpress/block-editor"; import { SelectControl } from "@wordpress/components"; import { registerBlockType } from "@wordpress/blocks"; import { useSelect } from "@wordpress/data"; import { useState } from "@wordpress/element"; interface selectOption { value: string, name: string } interface optionGroups { [label: string]: selectOption[] } registerBlockType( 'blockify/taxonomies', { name: 'blockify/taxonomies', title: 'Taxonomies', category: 'blockify', icon: 'tag', attributes: {}, edit: ( props: blockProps ) => { const [ selected, setSelected ] = useState( '' ); const { optionGroups } = useSelect<{ optionGroups: optionGroups }>( ( select ) => { const taxonomies: Array<{ [key: string]: any }> = select( 'core' ).getTaxonomies( { per_page: -1 } ); const selectOptions: optionGroups = {}; taxonomies?.forEach( taxonomy => { const terms: Array<{ [key: string]: string }> = select( 'core' ).getEntityRecords( 'taxonomy', taxonomy.slug, { per_page: -1 } ); terms?.forEach( term => { if ( ! selectOptions[taxonomy.name] ) { selectOptions[taxonomy.name] = []; } selectOptions[taxonomy.name].push( { value: term.id, name: term.name } ); } ); } ); return { optionGroups: selectOptions } } ) ?? {}; return <> <div> { selected ?? __( 'Select taxonomy' ) } </div> <InspectorControls> <SelectControl label={ __( 'Select taxonomy', 'blockify' ) } value={ selected } onChange={ ( selection ) => { setSelected( selection ) } } > { Object?.keys( optionGroups ?? {} )?.map( group => ( <optgroup label={ group }> { optionGroups[group].map( ( option: selectOption ) => ( <option value={ option.value }>{ option.name }</option> ) ) } </optgroup> ) ) } </SelectControl> </InspectorControls> </>; }, save: ( props ) => { } } );
Code language: JavaScript (javascript)