I’m new in developing Gutenberg-Blocks with ReactJS for WordPress.
At the moment I’m developing a block which contains all entries of my custom post type. The entries should be shown as a select-box in the block.
But I’ve got some problems with saving the selected value. After saving and reloading the page, the select-box shows the “select an option…” again.
My code in the index.js file:
import {registerBlockType} from '@wordpress/blocks';
import {withSelect} from '@wordpress/data';
import {SelectControl} from "@wordpress/components";
import {withState} from '@wordpress/compose';
const MySelectControl = withState({
chart: "0",
})
(
({chart, setState, ...props}) => (
<SelectControl
label="Bitte wählen Sie ein Diagramm aus: "
value={chart}
options={props.options}
onChange={(chart) => {
setState({chart});
}}
/>
)
);
registerBlockType('my_chart/charts', {
title: 'Diagramm',
icon: 'chart-bar',
category: 'widgets',
attributes: {
chart: {
type: 'number'
}
},
edit: withSelect((select) => {
const query = {per_page: -1};
return {
posts: select('core').getEntityRecords('postType', 'my_charts', query),
};
})
(
({posts, attributes, setAttributes}) => {
if (!posts) {
return 'Loading charts...';
}
if (posts && posts.length === 0) {
return 'No charts found';
}
let options = [];
// if posts found
if (posts) {
options.push({
value: 0,
label: 'Select an option...'
});
posts.forEach((post) => {
options.push(
{
value: post.id,
label: post.title.rendered
});
});
} else {
options.push({
value: 0,
label: 'Loading charts...'
});
}
return (<MySelectControl options={options}/>);
}
),
save: function (props) {
return null;
},
});
Does someone know what’s going wrong here? I’m not sure if I use the right way to display a select-box of entries of a custom post type. I think the problem is:
const MySelectControl = withState({
chart: "0",
})
I set the value every time to “0”. But how can I pass the already selected value to it?
If you need some more information please let me know.
Thanks,
Thorsten