i'm new to react and wanna ask how i can display this.state values in my wordpress frontend? (save.js)
edit.js:
import apiFetch from '@wordpress/api-fetch';
const { Component } = wp.element;
const { Spinner } = wp.components;
class Edit extends Component {
constructor(props) {
super(props);
this.state = {
list: [],
loading: true,
test: 'lorem ipsum'
}
}
componentDidMount() {
this.runApiFetch();
}
runApiFetch() {
apiFetch({ path: '/wp/v2/posts' })
.then(data => {
this.setState({
list: data,
loading: false
})
})
}
render() {
return(
<div>
{this.state.loading ? (
<Spinner />
) : (
<>
{this.state.list.map(post => {
return (
<div>
{ post.title.rendered }
</div>
)
}) }
</>
)}
</div>
);
}
}
export default Edit;
save in my index.js:
save() {
const { test } = this.state;
return (
<>
<div>{test}</ div>
</>
)
}
I got this error:
How i can display this.state values in wordpress frontend? Everything works in editor view.

The
save()function in save.js cannot access the internal state contained withinEditcausing the error seen.As you're new to React, I'd suggest starting your project with the WordPress Create Block tool which will make starting a project easier and setup a solid foundation to build from.
WordPress Gutenberg blocks are built differently compared to a straight ReactJS project and what you'd assume to be the 'state' is stored in the attributes, defined in
block.jsonso its accessible between theedit()andsave()functions. Theedit()function is what is displayed in the Editor to the User, where thesave()function in a static block is the content saved and rendered to the front end. So if you were displaying a list of posts in the Editor with apiFetch that was the "latest" or some other attribute that changes, you would store the parameters required in the block attributes then dynamically render the block on the frontend using those parameters in the block attributes.