Advertisement
Guest User

Untitled

a guest
Oct 16th, 2019
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.87 KB | None | 0 0
  1. /**
  2. * Post selector component
  3. * Use: <PostSelector numOfPosts="100" postType="custom_post_type" attributes={attributes} setAttributes={setAttributes} />
  4. */
  5.  
  6. const { apiFetch } = wp;
  7.  
  8. const { Component } = wp.element;
  9.  
  10. const { Spinner } = wp.components;
  11.  
  12. const { SelectControl } = wp.components;
  13.  
  14. const { decodeEntities } = wp.htmlEntities
  15.  
  16.  
  17. export class PostSelector extends Component {
  18.  
  19. constructor( props ) {
  20. super();
  21. this.state = { response: null };
  22. }
  23.  
  24. componentDidMount() {
  25.  
  26. this.isStillMounted = true;
  27.  
  28. if ( ! this.state.response ) {
  29. this.fetchPosts();
  30. }
  31. }
  32.  
  33. componentWillUnmount() {
  34. this.isStillMounted = false;
  35. }
  36.  
  37. fetchPosts() {
  38.  
  39. const {
  40. postType,
  41. numOfPosts
  42. } = this.props;
  43.  
  44. const path = `/wp/v2/${postType}?per_page=${numOfPosts}`;
  45.  
  46. return apiFetch( { path } )
  47. .then( ( response ) => {
  48. if ( this.isStillMounted && response ) {
  49. this.setState( { response: response } );
  50. }
  51. } )
  52. .catch( ( error ) => {
  53. if ( this.isStillMounted ) {
  54. this.setState( { response: {
  55. error: true,
  56. errorMsg: error.message,
  57. } } );
  58. }
  59. } );
  60. }
  61.  
  62. render() {
  63.  
  64. const response = this.state.response;
  65.  
  66. if ( ! response ) {
  67. return (
  68. <Spinner />
  69. );
  70. } else if ( response.error ) {
  71. return (
  72. <p>{ response.errorMsg }</p>
  73. );
  74. } else if ( ! response.length ) {
  75. return (
  76. <p>{ 'No menus found.' }</p>
  77. );
  78. }
  79.  
  80. let options = [ { label: 'Please Select One', value: null, disabled: true } ];
  81. response.map( ( post ) => (
  82. options.push( { label: decodeEntities( post.title.rendered ), value: post.id } )
  83. ) )
  84.  
  85. const {
  86. setAttributes,
  87. attributes,
  88. } = this.props;
  89.  
  90. const { post_id } = attributes;
  91.  
  92. return (
  93. <SelectControl
  94. label="Select a Post"
  95. value={ post_id }
  96. options={ options }
  97. onChange={ ( post_id ) => { setAttributes( { post_id } ) } }
  98. />
  99. );
  100. }
  101. }
  102.  
  103. export default PostSelector;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement