I'm developing a Gutenberg block and I need to show a dropdown with all the terms of a custom taxonomy in it. I'm using the useSelect
hook for retrieving this data, but it's not working because it gets stuck showing the Loading...
message and there are no errors in the console. I registered the taxonomy with the show_in_rest
arg set to true.
I don't know what I'm doing wrong. Any ideas?
const { registerBlockType } = wp.blocks;
const { Placeholder, SelectControl } = wp.components;
const { useSelect } = wp.data;
const blockAttributes = {
slug: {
type: 'string',
default: '',
},
};
export const name = 'my-plugin/my-terms-block';
export const settings = {
title: 'My Terms Block' ),
attributes: blockAttributes,
edit: ( props => {
const { attributes, className } = props;
const terms = useSelect( ( select ) =>
select( 'core' ).getEntityRecords( 'taxonomy', 'my_taxonomy', { per_page: -1, orderby: 'name', order: 'asc', _fields: 'name,slug' } )
);
const setSlug = value => {
props.setAttributes( { slug: value } );
};
if ( ! terms ) {
return 'Loading...';
}
if ( terms.length === 0 ) {
return 'No terms found' );
}
var options = [];
options.push( {
label: 'Select a term...',
value: ''
} );
for ( var i = 0; i < terms.length; i++ ) {
options.push( {
label: terms[i].name,
value: terms[i].slug
} );
}
return (
<Placeholder
key='my-terms-block'
label={ 'Terms Block' }
className={ className }>
<SelectControl
label={ 'Select a term:' }
value={ attributes.slug }
options={ options }
onChange={ setSlug }
/>
</Placeholder>
);
} ),
};
registerBlockType( name, settings );