WordPress PluginSidebar, TextControl setting and saving the default value

I apologize in advance for poor English.
I’m trying to rewrite the old plugin from add_meta_box to register_meta.
In theory, everything works as it should, except for adopting old values as defaults.
Old value API : oldKey format(json)
New value API: meta -> newKey (same oldKey)

Given that I’m a beginner in React.js, please help me how to attach default values to setMetaFieldValue and metaFieldValue.
file plugin.js

import "./editor.scss";
import icons from '../../components/icons'
import TitleField from '../../components/fields/meta-title';
import DescriptionField  from '../../components/fields/meta-description';
import CanonicalUrlField from '../../components/fields/meta-canonical-url';


const {Fragment} = wp.element
const { registerPlugin } = wp.plugins;
const { PluginSidebar, PluginSidebarMoreMenuItem } = wp.editPost;
const { registerBlockType } = wp.blocks;
const { PanelBody, TextControl, TextareaControl, CheckboxControl, PanelRow } = wp.components;
const { withSelect, withDispatch } = wp.data;

const PluginSidebarSeo = () => (
    <Fragment>
        <PluginSidebarMoreMenuItem target="plugin-sidebar-seo" icon={ icons.seo }>
            Seo
        </PluginSidebarMoreMenuItem>
        <PluginSidebar name="plugin-sidebar-seo" title="Seo" icon={ icons.seo }>
            <PanelBody title="Seo" icon={ icons.seo } initialOpen={ true }>
                <PanelRow>
                    <TitleField />
                </PanelRow>
                <PanelRow>
                    <DescriptionField />
                </PanelRow>
                <PanelRow>
                    <CanonicalUrlField />
                </PanelRow>
            </PanelBody>
        </PluginSidebar>
    </Fragment>
)

registerPlugin('seo', {render: PluginSidebarSeo});

file meta-title.js

/**
 * External dependencies.
 */
import React from 'react'

/**
 * WordPress dependencies.
 */
const { __ } = wp.i18n;
const { compose } = wp.compose;
const { withDispatch, withSelect } = wp.data;
const { TextControl } = wp.components;

class TitleField extends React.Component {
    constructor() {
        super()
    }
    render() {
        return (
            <div className="metatags-title-field">

                <TextControl
                    label={__("Title", "metatags")}
                    value={this.props.metaFieldValue}
                    onChange={this.props.setMetaFieldValue}
                />

            </div>
        )
    }
}

export default compose([

    withDispatch(( dispatch , props ) => {

        return {
            setMetaFieldValue: function( value ) {
                dispatch( 'core/editor' ).editPost( { meta: { meta_title: value } } );
            }
        }

    }),
    withSelect(( select , props ) => {

        return {
            metaFieldValue: select( 'core/editor' ).getEditedPostAttribute( 'meta' )[ 'meta_title' ],
        };

    }),

])( TitleField );

0

Leave a Comment