I have a custom block that shows the assigned taxonomy terms for the current post. I’m trying to show a loading spinner while those terms are loading in the background.

Let’s say I have a selector for a custom taxonomy that looks something like this:

const { withSelect } = wp.data;

const MyComponent = withSelect(select => {
  return {
    terms: select('core').getEntityRecords("taxonomy", "my_taxonomy", {
      _fields: 'id,name,slug'
    }),
  }
})(props => {
  console.log("taxonomies: ", props.terms);
  return (
    <ul>
      {props.terms.map(t => (
        <li key={term.id}>{term.name}</li>
      ))}
    </ul>
  );
});

When the editor loads and the taxonomy terms are fetched via some AJAX call the props.terms value changes to the following values during that time

  1. initial: props.terms = []
  2. at some point after the request fires: props.terms = null
  3. when the data is returned: props.terms = [term1, term2, ...]

I guess that whenever props.terms === null I could assume that the terms are loading, but I would prefer some kind of loading state from the store instead. Is that possible?

1 Answer
1

Yes, it’s possible and you’d use wp.data.select( 'core/data' ).isResolving().

Example based on your code:

const MyComponent = withSelect(select => {
  const { isResolving } = select( 'core/data' );
  const query = { _fields: 'id,name,slug' };
  return {
    terms: select('core').getEntityRecords("taxonomy", "my_taxonomy", query),
    isRequesting: isResolving( 'core', 'getEntityRecords', [ 'taxonomy', 'my_taxonomy', query ] )
  };
})(props => {
  if ( props.isRequesting ) {
    return (
      <div className="loading">
        Loading...
      </div>
    );
  }
  return (
    <ul>
      { props.terms.map( term => (<li key={ term.id }>{ term.name }</li>) ) }
    </ul>
  );
});

And you might also want to check the “edit” component for the Categories block.

Leave a Reply

Your email address will not be published. Required fields are marked *