Gutenberg block get categories in SelectControl

The problem is that calling wp.data.select triggers a fetch and the data takes some time to be available. Until that happens the value returned is an empty array.

My suggestion here is to use wp.data.useSelect, which is a React hook made specifically for this, so the component re-renders when there is a change in the data:

const MyComponent = () => {

    const categories = useSelect(select =>
        select('core').getEntityRecords('taxonomy', 'category')
    );

    const [categories_selected, setCategoriesSelected] = useState([]);

    return (
        <SelectControl
            multiple
            label={__('Cat')}
            options={categories.map(({id, name}) => ({label: name, value: id}))}
            onChange={(selected) => {
                // I haven't tested this code so I'm not sure what onChange returns.
                // But assuming it returns an array of selected values:
                setCategoriesSelected(selected)
            }}
            value={categories_selected}
        />
    );
};

This will also have the “issue” that the value on the first call of select('core').getEntityRecords('taxonomy', 'category') is empty. So you might want to consider it and return something different in the component if categories.length === 0.

If you really need to prevent this from happening, I guess you could call wp.data.select('core').getEntityRecords('taxonomy', 'category') in your script, close to the top, so when it is called by the component for the first time the data is already in the store.

Leave a Comment