0

I am using the following functions to get the selected category objects. It seems to always return no matches even though there are several. What am I missing here?

(function (wp) { const { useSelect, select, dispatch } = wp.data; const { subscribe } = wp.data; function getSelectedCategories() { const selectedCategories = select('core/editor').getEditedPostAttribute('categories'); const categories = select('core').getEntityRecords('taxonomy', 'category'); if (!categories || !selectedCategories || selectedCategories.length === 0) { return []; } return categories.filter(cat => selectedCategories.includes(cat.id)); } } 
1
  • have you looked at the useSelect react hook? It's very rare to see block editor components directly interfacing with data stores like that. Also what's the context this is being used in? Where and how this is used is very important but that information is missing here
    – Tom J Nowell
    CommentedSep 24, 2024 at 20:57

1 Answer 1

0

We need to modified the code with slight different approach. In this modified version of code we are using the useSelect hook to get the selected categories and categories and also ensure the data is available before attempting to filter it.

(function (wp) { const { useSelect } = wp.data; function getSelectedCategories() { // We are using useSelect hook to get the data from the store. const { selectedCategories, categories } = useSelect( ( select ) => { const selectedCategories = select('core/editor').getEditedPostAttribute( 'categories' ); const categories = select( 'core' ).getEntityRecords( 'taxonomy', 'category', { per_page: -1 } ); return { selectedCategories, categories }; }, []); // Here we are checking if categories and selectedCategories are available. if ( ! categories || ! selectedCategories || selectedCategories.length === 0 ) { return []; } // This is to filter categories to get the selected ones. return categories.filter( cat => selectedCategories.includes( cat.id ) ); } // This is the usage example. const selectedCategories = getSelectedCategories(); console.log( selectedCategories ); // This is for the debugging purpose. })( window.wp ); 
1
  • Adding , { per_page: -1 } definitely helped here.
    – Tommizzy
    CommentedSep 30, 2024 at 14:50

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.