when I update the attribute, the number of posts rendered in the block
don’t change
Yes, and that’s because you did not include the numberPosts
attribute in the second parameter (which is an array of dependencies) for useSelect()
, so the (memoized) value remains unchanged, even when the block’s state is changed, or that you selected a new number of posts via the range control.
So your useSelect()
should include the above dependency, i.e. use [ attributes.numberPosts ]
instead of []
as the 2nd parameter, like so:
const posts = useSelect( ( select ) => {
return select( 'core' ).getEntityRecords(
'postType',
'post',
{
'per_page': attributes.numberPosts
}
);
}, [ attributes.numberPosts ] ); // here, make sure you include all dependencies
Additionally, you should set a key
for your list items, e.g. <li key={ `post-${ post.id }` }>
.