1

I'm attempting to get the ID for either a tag / category by slug name within a Gutenberg sidebar plugin. I created the below function, but am still struggling with the results coming back null the first time (due to the delay by the API call behind GetEntityRecords). The second time I call data appears correctly.

Any thoughts?

PS: This function is executed "onClick" of a button within my component. The code sits outside of the component currently.

function GetTaxonomyId(taxonomy_slug, type){

    //Setup Locals
    let taxonomy_object = null;

    //Setup Queries
    const query = { slug: taxonomy_slug };    

    //Get terms
    select('core').getEntityRecords('taxonomy', type, query);

    //Subscribe to state changes for isResolving
    const unsubscribe = subscribe(() => {
        const { isResolving } = select( 'core/data' );

        //Build Args object
        const args = ['taxonomy', type, query];

        //Verify the queries have resolved
        if ( !isResolving('core', 'getEntityRecords', args)) {
            
            console.log('resolved');

            //Get values from the cache
            taxonomy_object = select('core').getEntityRecords('taxonomy', type, query);

            // We're done, so let's unsubscribe from the isResolving() check above.
            unsubscribe();

            //console.log(JSON.stringify(taxonomy_object)); //<-- This Shows as an empty object
        
            //Verify we have a valid object
            if(taxonomy_object){
                console.log('Object ID is ' + taxonomy_object[0].id);
                //return taxonomy_object[0].id;
            }
                      
        }else{
            console.log('still resolving');
        }
    })
}

Ref:

  1. How to use “getEntityRecords” for user data?

1 Answer 1

2

So... through some trial and error, I discovered that I'd gotten some of the logic wrong in order to detect and ensure the result of the API call (and subsequent state change) was treated properly.

I suspect that "other" state changes were firing and I was unsubscribing before I needed to - hence the unsubscribe has been moved to within the routine that checks for the data I require.

I've posted the solution below for anyone else that comes across this:

function ProcessTaxonomy(taxonomy_slug, type){

    //Setup Locals
    let taxonomy_object = null;

    //Setup Queries
    const query = { slug: taxonomy_slug, _fields: 'id,slug' };

    //Get terms
    select('core').getEntityRecords('taxonomy', type, query);

    //Subscribe to state changes for isResolving
    const unsubscribe = subscribe(() => {
        const { isResolving } = select( 'core/data' );

        //Build Args object
        const args = ['taxonomy', type, query];

        //Verify the queries have resolved
        if ( !isResolving('core', 'getEntityRecords', args)) {
            
            //Get values from the cache
            taxonomy_object = select('core').getEntityRecords('taxonomy', type, query);

            //Check length of array (do we have data to work with?)
            let length = (taxonomy_object ? taxonomy_object.length : 0);
        
            //Verify we have a valid object
            if(length > 0){

                // We're done, so let's unsubscribe from the isResolving() check above.
                unsubscribe(); 

                //Extract Taxonomy Item ID
                let taxonomy_item_id = taxonomy_object[0].id;
                
                // Add Taxonomies to UI
                switch (type) {
                    case 'post_tag':    //Tags
                        
                        AddTag(taxonomy_item_id); // Custom function to add tag to post and refresh the tag panel
                        break;

                    case 'category':    //Categories
                    
                        AddCategory(taxonomy_item_id); // Custom function to add category to post and refresh the category panel
                        break;                        
                
                    default:
                        break;
                }
            }
                      
        }else{
            // Still resolving
        }
    })
}

This can fire, take the time required to resolve and then update the post / UI as required (using the custom AddTag / AddCategory functions).

See this question on SO for more info on the custom functions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.