Correctly handling WordPress core data retrieval in Gutenberg

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.

Leave a Comment