import React, { useEffect, useState } from 'react'; import styled from 'styled-components/macro'; import tw from 'twin.macro'; import Input from '@/components/elements/Input'; import Label from '@/components/elements/Label'; import { Location } from '@/api/admin/locations/getLocations'; import searchLocations from '@/api/admin/locations/searchLocations'; import InputSpinner from '@/components/elements/InputSpinner'; import { debounce } from 'debounce'; const Dropdown = styled.div<{ expanded: boolean }>` ${tw`absolute mt-1 w-full rounded-md bg-neutral-900 shadow-lg z-10`}; ${props => !props.expanded && tw`hidden`}; `; export default ({ defaultLocation }: { defaultLocation: Location }) => { const [ loading, setLoading ] = useState(false); const [ expanded, setExpanded ] = useState(false); const [ location, setLocation ] = useState(defaultLocation); const [ locations, setLocations ] = useState([]); const [ inputText, setInputText ] = useState(''); const onFocus = () => { setInputText(''); setLocations([]); setExpanded(true); }; const onBlur = () => { // setInputText(location.short); // setExpanded(false); }; const search = debounce((query: string) => { if (!expanded) { return; } if (query === '') { setLocations([]); return; } setLoading(true); searchLocations({ short: query }).then((locations) => { console.log(locations); setLocations(locations); }).then(() => setLoading(false)); }, 200); const selectLocation = (location: Location) => { setLocation(location); }; useEffect(() => { setInputText(location.short); setExpanded(false); }, [ location ]); return (
{ setInputText(e.currentTarget.value); search(e.currentTarget.value); }} />
    {locations.map(l => ( l.id === location.id ?
  • selectLocation(l)}>
    {l.short}
  • :
  • selectLocation(l)}>
    {l.short}
  • ))}
); };