Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Post selector component
- * Use: <PostSelector numOfPosts="100" postType="custom_post_type" attributes={attributes} setAttributes={setAttributes} />
- */
- const { apiFetch } = wp;
- const { Component } = wp.element;
- const { Spinner } = wp.components;
- const { SelectControl } = wp.components;
- const { decodeEntities } = wp.htmlEntities
- export class PostSelector extends Component {
- constructor( props ) {
- super();
- this.state = { response: null };
- }
- componentDidMount() {
- this.isStillMounted = true;
- if ( ! this.state.response ) {
- this.fetchPosts();
- }
- }
- componentWillUnmount() {
- this.isStillMounted = false;
- }
- fetchPosts() {
- const {
- postType,
- numOfPosts
- } = this.props;
- const path = `/wp/v2/${postType}?per_page=${numOfPosts}`;
- return apiFetch( { path } )
- .then( ( response ) => {
- if ( this.isStillMounted && response ) {
- this.setState( { response: response } );
- }
- } )
- .catch( ( error ) => {
- if ( this.isStillMounted ) {
- this.setState( { response: {
- error: true,
- errorMsg: error.message,
- } } );
- }
- } );
- }
- render() {
- const response = this.state.response;
- if ( ! response ) {
- return (
- <Spinner />
- );
- } else if ( response.error ) {
- return (
- <p>{ response.errorMsg }</p>
- );
- } else if ( ! response.length ) {
- return (
- <p>{ 'No menus found.' }</p>
- );
- }
- let options = [ { label: 'Please Select One', value: null, disabled: true } ];
- response.map( ( post ) => (
- options.push( { label: decodeEntities( post.title.rendered ), value: post.id } )
- ) )
- const {
- setAttributes,
- attributes,
- } = this.props;
- const { post_id } = attributes;
- return (
- <SelectControl
- label="Select a Post"
- value={ post_id }
- options={ options }
- onChange={ ( post_id ) => { setAttributes( { post_id } ) } }
- />
- );
- }
- }
- export default PostSelector;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement