diff --git a/src/components/SearchBox.tsx b/src/components/SearchBox.tsx index a5c9112..62cfadd 100644 --- a/src/components/SearchBox.tsx +++ b/src/components/SearchBox.tsx @@ -4,24 +4,35 @@ import { Box, TextInput } from 'grommet'; import { FormSearch } from 'grommet-icons'; import { debounce } from 'lodash'; -const SEARCH_ARTIST = gql` +import { Artists, Artist } from '../interfaces'; + +const QUERY_ARTIST_ALBUMS = gql` query Artist($byName: String!) { queryArtists(byName: $byName) { name + image + id + albums { + name + image + id + } } } `; export const SearchBox = () => { const [value, setValue] = useState(''); - const [getArtist, { loading, data }] = useLazyQuery(SEARCH_ARTIST); - const [suggestions, setSuggestions] = useState(['']); - // TODO: Find a solution to have suggestions not showing when empty + const [getArtists, { data }] = useLazyQuery(QUERY_ARTIST_ALBUMS); + const [artists, setArtists] = useState(undefined); + const [suggestions, setSuggestions] = useState( + undefined, + ); // Debounce the database query, based on the following article: // https://dev.to/reflexgravity/use-lodash-debouce-inside-a-functional-component-in-react-4g5j const updateQuery = () => { - getArtist({ variables: { byName: value } }); + getArtists({ variables: { byName: value } }); }; const delayedQuery = useCallback(debounce(updateQuery, 500), [value]); @@ -30,6 +41,7 @@ export const SearchBox = () => { setValue(e.target.value); }; + // TODO: Maybe merge the two use effects? useEffect(() => { delayedQuery(); @@ -38,15 +50,16 @@ export const SearchBox = () => { }, [value, delayedQuery]); useEffect(() => { - // TODO: Maybe merge the two use effects? - if (data) { - const mapSuggestions: string[] = data.queryArtists.map( - (el: { name: string }) => { + if (data && data.queryArtists !== []) { + // Limit artists to 5 + const updatedArtists = data.queryArtists.slice(0, 5); + const updatedSuggestions: string[] = updatedArtists.map( + (el: Artist) => { return el.name; }, ); - const updatedSuggestions = mapSuggestions.slice(0, 5); setSuggestions(updatedSuggestions); + setArtists(updatedArtists); } }, [data]); @@ -63,7 +76,7 @@ export const SearchBox = () => { placeholder='Type an artist name' icon={} dropHeight='large' - suggestions= {suggestions} + suggestions={suggestions} /> ); diff --git a/src/interfaces/index.ts b/src/interfaces/index.ts new file mode 100644 index 0000000..061214a --- /dev/null +++ b/src/interfaces/index.ts @@ -0,0 +1,14 @@ +export interface Album { + name: string; + image: string; + id: string; +} + +export interface Artist { + name: string; + image: string; + id: string; + albums: Album[]; +} + +export type Artists = Artist[]; \ No newline at end of file