import React, { Component } from 'react'; import { __ } from '@wordpress/i18n'; import { Modal, Button, SelectControl } from '@wordpress/components'; import apiFetch from '@wordpress/api-fetch'; import Loader from '../Loader/Loader'; import './Inserter.css'; interface WPPost { ID: string; post_title: string; } interface InserterProps { pickTest: (id: string) => void; removeSelf: () => void; insertNew: () => void; } interface InserterState { value: string; isLoading: boolean; isPicking: boolean; options: WPPost[]; } class Inserter extends Component { constructor(props: InserterProps) { super(props); this.state = { value: '', isLoading: true, isPicking: false, options: [], }; } componentDidMount(): void { apiFetch({ path: 'ab-testing-for-wp/v1/get-posts-by-type?type=abt4wp-test' }) .then((options) => { if (options.length === 0) { this.insertNew(); return; } this.setState({ isLoading: false, value: options[0].ID, options, }); }); } insertNew = (): void => { const { insertNew } = this.props; insertNew(); }; cancelInsert = (): void => { const { removeSelf } = this.props; removeSelf(); }; insertExisting = (): void => { const { pickTest } = this.props; const { value } = this.state; pickTest(value); }; render(): React.ReactElement { const { value, isLoading, isPicking, options, } = this.state; if (isLoading) return
; return ( {isPicking ? (
({ label: option.post_title, value: option.ID, }))} onChange={(newValue): void => this.setState({ value: newValue })} />
) : (
)}
); } } export default Inserter;