Skip to content

Instantly share code, notes, and snippets.

@kreamweb
Created January 27, 2022 07:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kreamweb/36f9484727714b68b69852aa7280b3b8 to your computer and use it in GitHub Desktop.
Save kreamweb/36f9484727714b68b69852aa7280b3b8 to your computer and use it in GitHub Desktop.
import apiFetch from '@wordpress/api-fetch';
import {addQueryArgs} from '@wordpress/url';
import {getCurrentPost} = wp.data.select('core/editor');
const api_path = '/wp/v2/pdf_template/'; //this is the slug of rest_endpoint set inside the register_post_type
function TemplateList() {
function handleOnClick(template) {
const currentPost = getCurrentPost();
var newPost = currentPost;
newPost.content = template.content;
const query = {
ywraq_edit_pdf_template: true,
};
apiFetch({
//adding the id inside the api_path the post will be update otherwise a new post will be created and the new object passed in data (then)
path: addQueryArgs(api_path + currentPost.id, query),
data: Object.assign({}, newPost),
method: 'POST',
}).then((data) => {
console.log(data);
wp.data.dispatch('core/editor').editPost( {content: template.content }); //change the current post inside the wp.data
wp.data.dispatch( 'core/block-editor' ).resetBlocks( wp.blocks.parse( template.content ) ); //render the block of the new content inside the editor
}).catch((error) => {
console.log(error);
});
}
return (
<div onClick={() => handleOnClick(template1)}>{template1.id}</div>
);
}
export default TemplateList;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment