Skip to content

Commit

Permalink
useEffect to fetchContactForms
Browse files Browse the repository at this point in the history
  • Loading branch information
takayukister committed May 6, 2024
1 parent 2867463 commit 0d7d753
Show file tree
Hide file tree
Showing 4 changed files with 10 additions and 42 deletions.
36 changes: 1 addition & 35 deletions includes/block-editor/block-editor.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ function wpcf7_init_block_editor_assets() {

$assets = wp_parse_args( $assets, array(
'dependencies' => array(
'react',
'wp-api-fetch',
'wp-block-editor',
'wp-blocks',
Expand Down Expand Up @@ -49,38 +50,3 @@ function wpcf7_init_block_editor_assets() {
)
);
}


add_action(
'enqueue_block_editor_assets',
'wpcf7_enqueue_block_editor_assets',
10, 0
);

function wpcf7_enqueue_block_editor_assets() {
$contact_forms = array_map(
static function ( $contact_form ) {
return array(
'id' => $contact_form->id(),
'hash' => $contact_form->hash(),
'slug' => $contact_form->name(),
'title' => $contact_form->title(),
'locale' => $contact_form->locale(),
);
},
WPCF7_ContactForm::find( array(
'posts_per_page' => 20,
'orderby' => 'modified',
'order' => 'DESC',
) )
);

wp_add_inline_script(
'contact-form-7-block-editor',
sprintf(
'window.wpcf7 = {contactForms:%s};',
wp_json_encode( $contact_forms )
),
'before'
);
}
2 changes: 1 addition & 1 deletion includes/block-editor/index.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 8 additions & 2 deletions includes/block-editor/src/edit.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { __ } from '@wordpress/i18n';
import { useState } from '@wordpress/element';
import { useState, useEffect } from '@wordpress/element';
import { useBlockProps, InspectorControls } from '@wordpress/block-editor';

import {
Expand Down Expand Up @@ -31,9 +31,15 @@ export default function ContactFormSelectorEdit( { attributes, setAttributes } )
};

const [ contactForms, setContactForms ] = useState(
() => createMap( window.wpcf7.contactForms ?? [] )
() => createMap( [] )
);

useEffect( () => {
fetchContactForms().then( response => {
setContactForms( createMap( response ) );
} );
}, [] );

const blockProps = {
className: 'components-placeholder',
style: {
Expand Down
4 changes: 0 additions & 4 deletions includes/block-editor/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,6 @@ import { __ } from '@wordpress/i18n';
import { registerBlockType } from '@wordpress/blocks';
import { useBlockProps } from '@wordpress/block-editor';

window.wpcf7 = window.wpcf7 ?? {
contactForms: [],
};

import icon from './icon';
import edit from './edit';
import transforms from './transforms';
Expand Down

0 comments on commit 0d7d753

Please sign in to comment.