How to properly add custom entities in Gutenberg

I stumbled upon this question long after it was asked – but for the sake of all readers in search on how to use this indeed poorly documented function, here is my answer:

Do not use addEntities in the filter. It is not the same logic as in PHP backend. Putting it into BlockEdit filter indeed creates problem of calling it when registering each block, and hence you have to use this workaround which you did put in your code.

Call it simply in the main script which is registered with block (usually index.js) or you can call it in edit.js (if your block has separate file for edit). What is important is to call it outside of Edit function, or any WordPress React element, since that will cause the same problems as you experienced, because it is called too late and/or repeatably.

Additionaly, if you look at the definition of getEntityRecords, you will observe that it has fourth parameter (actually third, since you don’t provide state when calling it) query, which you can use to obtain only fields that you need, without the need to build custom REST endpoints.

In global REST parameters of WordPress, there is a _fields parameter which you should use as property of object in that call, like so (this is a call inside Edit function):

const postTitlesList = useSelect(select => select('core').getEntityRecords('postType', 'post', { ['_fields']: 'id,title' }), []);