WordPress Gutenberg-Block with ESNext (withState, withSelect)

Okay guys, I’ve got a solution:

import {withSelect} from '@wordpress/data';
import {SelectControl} from "@wordpress/components";
import ReactSpinner from 'react-bootstrap-spinner'
import ServerSideRender from '@wordpress/server-side-render';

const MySelectControl =
    (
        ({chart, setAttributes, ...props}) => (
            <SelectControl
                label="Bitte wählen Sie ein Diagramm aus: "
                value={chart ? parseInt(chart) : 0}
                options={props.options}
                onChange={(chart) => {
                    setAttributes({
                        chart: chart
                    });
                }}
            />
        )
    );

registerBlockType('my_chart/charts', {
    title: 'Diagramm',
    icon: 'chart-bar',
    category: 'widgets',
    attributes: {
        chart: {
            type: 'string'
        }
    },
    edit: withSelect((select) => {
        const query = {per_page: -1};
        return {
            posts: select('core').getEntityRecords('postType', 'my_charts', query),
        };
    })
    (
        ({posts, setAttributes, className, attributes}) => {
            if (!posts) {
                return <p className={className}>
                    <ReactSpinner type="border" size="2">
                        <span className="sr-only">Diagramme werden geladen...</span>
                    </ReactSpinner>
                </p>;
            }
            if (posts && posts.length === 0) {
                return '<p>Keine Diagramme gefunden</p>';
            }
            let options = [];

            // if posts found
            if (posts) {
                options.push({
                    value: 0,
                    label: 'Bitte auswählen...'
                });
                posts.forEach((post) => {
                    options.push(
                        {
                            value: post.id,
                            label: post.title.rendered
                        });
                });
            }

            return (
                <div className={className}>
                    <MySelectControl key={attributes.chart}
                                     setAttributes={setAttributes}
                                     options={options}
                                     chart={attributes.chart}/>

                    <ServerSideRender
                        block="my-charts-importer/charts"
                        attributes={ attributes }
                    />
                </div>
            );
        }
    ),
    save: function () {
        return null;
    },
});```

Leave a Comment