1

I tried to understand the fragment of an example here https://developer.wordpress.org/block-editor/packages/packages-data/ about useSelect.

function DisplayTOC(props) {
  return (  <ServerSideRender block={props.name} attributes={props.attributes} />);
}


registerBlockType('simpletoc/toc', {
  title: __('SimpleTOC', 'simpletoc'),
  icon: simpletocicon,
  category: 'layout',
  edit: function(props) {
    return (

      <p className={props.className}>
        <AsyncModeProvider value={ true }>
          <DisplayTOC props={props}/>
        </AsyncModeProvider>
      </p>

    )
  },
  save: props => {
    return null;
  },
});

So my guess is that the Async method needs to know when to sync with useSelect. But where? In the documentation there is this function:

function BlockCount() {
  const count = useSelect( ( select ) => {
    return select( 'core/block-editor' ).getBlockCount()
  }, [] );

  return count;
}

So if a new block is added return the count. But when is this function called? I added it to the code and nothing happens.

1 Answer 1

2

It's called when the component is first rendered, then again when the dependencies declared in the second parameter change:

deps Array: If provided, this memoizes the mapSelect so the same mapSelect is invoked on every state change unless the dependencies change.

So don't pass that array, and it will work as you expected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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