I've been banging my head on this for a bit now.
I'm trying to create a simple wordpress block that fetches custom post types from the rest api, then displays the fetched posts via react. It only needs to do this, and requires no other editor functionality.
However, I'm a bit of a react/wp noob and I may be fundamentally misunderstanding how wordpress react functions, as I can't seem to get anywhere.
Here is my code so far:
class oupSeriesBlock extends Component {
constructor(props) {
super(props);
this.state = {data: []};
}
getOupSeries() {
console.log('mounted');
apiFetch({
path: 'wp/v2/oup_series'
}).then((response) => {
this.state = {data: response}
console.log(this.state);
})
}
componentDidMount() {
this.getOupSeries();
}
render() {
return(
<div>
Test
{this.state.data.length > 0 ? this.state.data.map(data => <div>{data.id}</div>) : 'empty'}
</div>
)
}
}
registerBlockType('cb/oup-series', {
title: 'OUP Book Series',
apiVersion: 2,
category: 'cb-layout',
icon: 'book-alt',
description: 'Shows list of OUP book series',
keywords: ['book', 'series', 'oup'],
edit: () => {
const blockProps = useBlockProps();
return (
<div {...blockProps}>
<div>OUP Series List</div>
</div>
)
},
save: oupSeriesBlock
});
The block is available and rendering without error but is not displaying any data, only 'Test' is rendered.
The rest route is definitely functioning correctly as I've tested it, but componentDidMount()
is never being called.
this.state.data.map
also works correctly when constructed with dummy data.
I've read through multiple examples and tutorials, but I'm having trouble applying them to my problem, if anyone could help it would be greatly appreciated.
useEffect
hook which can be used to fetch the posts more efficiently. Likewise it is an antipattern to talk directly to the REST API to fetch posts, there are more efficient cached APIs already built into the block editor for listing entities