I really have hard time to understand react. I try to find headings in my blocks and put them in a constant. So far so good. I can confirm this works when I do a console.info(headings) after I found them in the blocks.
Now I try to save this array as an attribute. It does not matter if I define one in registerBlockType first or if I just try to set them with
props.setAttributes( { headings: headings } );
If I do so, I get this error:
Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.
So I think this is some kind of recursion. But why does this happen? If I remove props.setAttributes it works but of course I don't have any attribute I get set my heading from.
registerBlockType( 'simpletoc/toc', {
title: __( 'SimpleTOC', 'simpletoc' ),
icon: listulicon,
category: 'layout',
attributes: {
headings: {
type: 'array'
},
},
edit: function ( props ) {
const headings = find_headings( props );
console.info(headings)
props.setAttributes( { headings: headings } );
return <Toc {...props} />;
},
save: function ( props ) {
return <Toc {...props} />;
},
} );
function Toc( props ) {
return <p className={ props.className }>
<h2 class="simpletoc-title">{ __( 'Table of Contents', 'simpletoc' ) }</h2>
<ul class="simpletoc">
{ props.headings }
</ul>
</p>;
}
function find_headings ( props ){
const data = wp.data.select( 'core/block-editor' );
const blocks = data.getBlocks();
const headings = blocks.map( ( item, index ) => {
if ( item.name === 'core/heading' ) {
var slug = '';
var hashslug = '';
var blockId = ( item.clientId );
slug = item.attributes.content;
//wp.data.dispatch( 'core/editor' ).updateBlockAttributes( blockId, { anchor: slug } );
hashslug = '#' + slug;
return <li><a href={hashslug}>{item.attributes.content}</a></li>;
}
} );
return {headings};
}