import React, { useState, useEffect } from "react"; import "./packages/combobox/styles.css"; import { Combobox, ComboboxInput, ComboboxList, ComboboxOption, ComboboxOptionText, ComboboxPopup } from "./packages/combobox/index"; import { useThrottle } from "use-throttle"; import uniqBy from "lodash.uniqby"; const styles = { option: { display: "flex", alignItems: "center", paddingRight: 10 }, imageWrapper: { background: "#eee", width: 30, height: 30, textAlign: "center" }, optionTextWrapper: { marginLeft: 10, whiteSpace: "nowrap", textOverflow: "ellipsis", overflow: "hidden" } }; export default function ITunes() { const [searchTerm, setSearchTerm] = useState(null); const songs = useSongSearch(searchTerm); const handleSearchTermChange = event => setSearchTerm(event.target.value); return (

iTunes Search

{songs && songs.map(song => (
{song.collectionName}
))}
); } async function fetchSongs(value) { try { let res = await fetch(`https://itunes.now.sh/?term=${value}`); let json = await res.json(); let songs = json.results.filter(song => song.trackName); let unique = uniqBy( songs, song => `${song.trackName}, ${song.collectionName}` ); return unique.slice(0, 10); } catch (e) { return Promise.resolve(null); } } function useSongSearch(searchTerm) { const [results, setResults] = useState([]); const throttled = useThrottle(searchTerm, 500); useEffect( () => { if (throttled) { if (throttled.trim() !== "") { let current = true; console.log("fetching", throttled); fetchSongs(throttled).then(results => { console.log("fetch finished", throttled); if (current) { console.log("setting results", throttled); setResults(results); } }); return () => (current = false); } } }, [throttled] ); return results; }