spoti-search/src/components/SearchBox.tsx

83 lines
2.0 KiB
TypeScript

import React, { useState, useCallback, useEffect } from 'react';
import { gql, useLazyQuery } from '@apollo/client';
import { Box, TextInput } from 'grommet';
import { FormSearch } from 'grommet-icons';
import { debounce } from 'lodash';
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 [inputValue, setInputValue] = useState('');
const [getArtists, { data }] = useLazyQuery(QUERY_ARTIST_ALBUMS);
const [artists, setArtists] = useState<Artists | undefined>(undefined);
const [suggestions, setSuggestions] = useState<string[] | undefined>(
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 = () => {
getArtists({ variables: { byName: inputValue } });
};
const delayedQuery = useCallback(debounce(updateQuery, 500), [inputValue]);
const handleChange = (e: any) => {
setInputValue(e.target.value);
};
useEffect(() => {
delayedQuery();
// Cancel previous debounce calls during useEffect cleanup.
return delayedQuery.cancel;
}, [inputValue, delayedQuery]);
// TODO: Maybe merge the two use effects?
useEffect(() => {
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;
},
);
setSuggestions(updatedSuggestions);
setArtists(updatedArtists);
}
}, [data]);
return (
<Box
as='section'
direction='row'
justify='center'
margin={{ vertical: 'large' }}
>
<TextInput
value={inputValue}
onChange={handleChange}
placeholder='Type an artist name'
icon={<FormSearch color='plain' />}
dropHeight='large'
suggestions={suggestions}
/>
</Box>
);
};