Can the multiple calls be combined inside just one
useSelect
selector?
Yes, and here’s an example where my useSelect()
returns an object that I unpack using the destructuring assignment (e.g. const { a, b } = myFunc()
where myFunc()
returns { a: 'foo', b: 123 }
):
const { groups, selectedGroup, faqs } = useSelect( ( select ) => {
const { getEntityRecords } = select( 'core' );
// The args are identical for both "groups" and selectedGroup, so I put them in a constant.
const groupsArgs = { per_page: -1, orderby: 'name', order: 'asc', _fields: 'id,name,slug' };
const selectedGroup = getEntityRecords( 'taxonomy', 'faq_group', groupsArgs )?.find(
( term ) => term.slug === attributes.group
);
return {
groups: getEntityRecords( 'taxonomy', 'faq_group', groupsArgs ),
faqs: getEntityRecords( 'postType', 'faq', { faq_group: [ selectedGroup?.id ] } ),
selectedGroup,
};
}, [ attributes.group ] );
If you do not actually need to access the selectedGroup
from outside the useSelect()
callback, then you can omit selectedGroup
from the list, i.e. use just const { groups, faqs } = useSelect( ... )
, and then remove the selectedGroup,
(the third line) from the return value.
And actually, instead of calling getEntityRecords()
twice with the same args, you could call it just once:
const { groups, selectedGroup, faqs } = useSelect( ( select ) => {
const { getEntityRecords } = select( 'core' );
const groupsArgs = { per_page: -1, orderby: 'name', order: 'asc', _fields: 'id,name,slug' };
const groups = getEntityRecords( 'taxonomy', 'faq_group', groupsArgs );
const selectedGroup = groups?.find( ( term ) => term.slug === attributes.group );
return {
groups,
selectedGroup,
faqs: getEntityRecords( 'postType', 'faq', { faq_group: [ selectedGroup?.id ] } ),
};
}, [ attributes.group ] );