| 1 |
import { registerBlockType } from '@wordpress/blocks'; |
| 2 |
import { SelectControl } from '@wordpress/components'; |
| 3 |
import { useState, useEffect } from '@wordpress/element'; |
| 4 |
import apiFetch from '@wordpress/api-fetch'; |
| 5 |
import icons from './icon'; |
| 6 |
|
| 7 |
wp.blocks.updateCategory("ovation-sliders", { icon: icons.slider }); |
| 8 |
|
| 9 |
const fetchAllPosts = async () => { |
| 10 |
let allPosts = []; |
| 11 |
let page = 1; |
| 12 |
let morePostsAvailable = true; |
| 13 |
|
| 14 |
while (morePostsAvailable) { |
| 15 |
const posts = await apiFetch({ path: `/wp/v2/ova_elems?per_page=100&page=${page}` }); |
| 16 |
allPosts = [...allPosts, ...posts]; |
| 17 |
morePostsAvailable = posts.length === 100; |
| 18 |
page++; |
| 19 |
} |
| 20 |
|
| 21 |
return allPosts; |
| 22 |
}; |
| 23 |
|
| 24 |
registerBlockType('ova-elems/ovation-sliders', { |
| 25 |
title: 'Ovation Sliders', |
| 26 |
icon: icons.slider, |
| 27 |
category: 'Ovation Sliders', |
| 28 |
attributes: { |
| 29 |
selectedPost: { |
| 30 |
type: 'number', |
| 31 |
default: null, |
| 32 |
} |
| 33 |
}, |
| 34 |
edit: ({ attributes, setAttributes }) => { |
| 35 |
const { selectedPost } = attributes; |
| 36 |
const [posts, setPosts] = useState([]); |
| 37 |
const [loading, setLoading] = useState(true); |
| 38 |
|
| 39 |
useEffect(() => { |
| 40 |
fetchAllPosts() |
| 41 |
.then((fetchedPosts) => { |
| 42 |
setPosts(fetchedPosts); |
| 43 |
setLoading(false); |
| 44 |
}) |
| 45 |
.catch((error) => { |
| 46 |
console.error(error); |
| 47 |
setLoading(false); |
| 48 |
}); |
| 49 |
}, []); |
| 50 |
|
| 51 |
const postOptions = posts.map(post => ({ |
| 52 |
label: post.title.rendered, |
| 53 |
value: post.id, |
| 54 |
})); |
| 55 |
|
| 56 |
postOptions.unshift({ label: 'Select a post', value: null }); |
| 57 |
|
| 58 |
return ( |
| 59 |
<div> |
| 60 |
{loading ? ( |
| 61 |
<p>Loading posts...</p> |
| 62 |
) : ( |
| 63 |
<SelectControl |
| 64 |
label="Select a Post" |
| 65 |
value={selectedPost} |
| 66 |
options={postOptions} |
| 67 |
onChange={(newPost) => setAttributes({ selectedPost: parseInt(newPost, 10) })} |
| 68 |
/> |
| 69 |
)} |
| 70 |
</div> |
| 71 |
); |
| 72 |
}, |
| 73 |
save: ({ attributes }) => { |
| 74 |
return null; |
| 75 |
} |
| 76 |
}); |
| 77 |
|