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 );
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
If you use the _fields argument, then it needs to include id. Otherwise, getEntityRecords() will always return a null, even if the REST API request succeeded.
So to fix the issue in question, you just need to add id to your args, i.e. _fields: 'id,name,slug'.
You should also know that per_page is limited to 100, so even if you set it to a greater number or even -1 (which means all), the value is always set to max 100.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0