2

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?

2

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.

  • 1
    Thank you @sally-cj - Now my loading indicator kicks in immediately as well. Before I had that weird case where it went from "No terms" --> "Loading" --> "Actual asigned terms". – Ahrengot Aug 8 at 21:02

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.