import { useState, useEffect } from '@wordpress/element'; import apiFetch from '@wordpress/api-fetch'; import { TextControl } from '@wordpress/components'; import { __ } from '@wordpress/i18n'; export default function LinkPicker(props) { const [activeKeyword, setActiveKeyword] = useState(''); const [links, setLinks] = useState< Array<{ id: number; url: string; title: string; post_type: string }> >([]); const [activeLink, setActiveLink] = useState({ url: '', title: '', }); useEffect(() => { if (activeKeyword === '') return; setLinks(null); apiFetch({ path: `/blockbite/v1/block-helpers/get-links/${activeKeyword}`, }).then( ( links: Array<{ id: number; url: string; title: string; post_type: string; }> | null ) => { if (links?.length) { setLinks([...links]); } else { setLinks([]); } } ); }, [activeKeyword]); useEffect(() => { if (activeLink.url !== '') { props.parentCallback(activeLink); } }, [activeLink]); return ( <>
setActiveKeyword(value)} help={__('Type a post, page, title', 'blockbitelinks')} /> {activeKeyword ? (
[ setActiveLink({ ...link }), setActiveKeyword(''), ]} />
) : null}
); } function LinkList({ links, onActiveLink }) { const list = []; if (links === null) { return

Loading...

; } else if (links.length === 0) { return

No Results

; } else { // iterate over the links and show img with icon based on icon_url and icon links.forEach((link) => { list.push( // add key
onActiveLink(link)} > {link.title} {link.url} {link.post_type}
); }); return list; } }