diff --git a/assets/js/blocks/related-posts/Edit.js b/assets/js/blocks/related-posts/Edit.js
index 491102f966..17816f01dc 100644
--- a/assets/js/blocks/related-posts/Edit.js
+++ b/assets/js/blocks/related-posts/Edit.js
@@ -1,109 +1,105 @@
/**
* WordPress dependencies.
*/
+import apiFetch from '@wordpress/api-fetch';
import { AlignmentToolbar, BlockControls, InspectorControls } from '@wordpress/block-editor';
import { PanelBody, Placeholder, Spinner, QueryControls } from '@wordpress/components';
-import { Fragment, Component, RawHTML } from '@wordpress/element';
+import { Fragment, RawHTML, useEffect, useState } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import { addQueryArgs } from '@wordpress/url';
/**
- * Edit component
+ * Related Posts block edit component.
+ *
+ * @param {object} props Component props.
+ * @param {object} props.attributes Block attributes.
+ * @param {string} props.className Additional CSS class(es).
+ * @param {object} props.context Block context,
+ * @param {Function} props.setAttributes Attribute setter.
+ * @returns {Function} Component element.
*/
-class Edit extends Component {
+const RelatedPostsEdit = ({ attributes, className, context, setAttributes }) => {
+ const { alignment, number } = attributes;
+ const [posts, setPosts] = useState(false);
+
/**
- * Setup class
- *
- * @param {object} props Component properties
+ * Related posts, limited by the selected number.
*/
- constructor(props) {
- super(props);
-
- this.state = {
- posts: false,
- };
- }
+ const displayPosts = posts.length > number ? posts.slice(0, number) : posts;
/**
- * Load preview data
+ * Initialize block.
*/
- componentDidMount() {
+ const handleInit = () => {
const urlArgs = {
number: 100,
};
- // Use 0 if in the Widgets Screen
- const { context: { postId = 0 } = {} } = this.props;
+ const { postId = 0 } = context;
- wp.apiFetch({
+ apiFetch({
path: addQueryArgs(`/wp/v2/posts/${postId}/related`, urlArgs),
})
.then((posts) => {
- this.setState({ posts });
+ setPosts(posts);
})
.catch(() => {
- this.setState({ posts: false });
+ setPosts(false);
});
- }
+ };
- render() {
- const {
- attributes: { alignment, number },
- setAttributes,
- className,
- } = this.props;
- const { posts } = this.state;
-
- const displayPosts = posts.length > number ? posts.slice(0, number) : posts;
+ /**
+ * Effects.
+ */
+ useEffect(handleInit, [context]);
- return (
-
- {displayPosts.map((post) => {
- const titleTrimmed = post.title.rendered.trim();
- return (
-
- )}
-