How can i display this.state value in save.js?

23 Views Asked by At

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:

enter image description here

How i can display this.state values in wordpress frontend? Everything works in editor view.

1

There are 1 best solutions below

0
S.Walsh On

The save() function in save.js cannot access the internal state contained within Edit causing 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.json so its accessible between the edit() and save() functions. The edit() function is what is displayed in the Editor to the User, where the save() 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.