From 0e6455b90c115cd8e332476a320f542cee1c6899 Mon Sep 17 00:00:00 2001 From: Angus Morton Date: Thu, 14 Apr 2022 14:00:31 +1000 Subject: [PATCH] =?UTF-8?q?=EF=BB=BFDebounce=20autocomplete=20suggestions?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/components/Autocomplete/Autocomplete.tsx | 22 +++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/src/components/Autocomplete/Autocomplete.tsx b/src/components/Autocomplete/Autocomplete.tsx index d2de0fc..d64e119 100644 --- a/src/components/Autocomplete/Autocomplete.tsx +++ b/src/components/Autocomplete/Autocomplete.tsx @@ -1,7 +1,10 @@ import { useEffect, useState } from "react"; import axios from "axios"; import styled from "styled-components"; -import Autosuggest from "react-autosuggest"; +import Autosuggest, { + OnSuggestionSelected, + SuggestionsFetchRequested, +} from "react-autosuggest"; type AutocompleteProps = { startCanonical: string; @@ -46,9 +49,9 @@ export function Autocomplete({ setSuggestions([])} - onSuggestionsFetchRequested={({ value }) => { + onSuggestionsFetchRequested={debounce(({ value }) => { getSuggestions(value); - }} + })} onSuggestionSelected={(_, result) => onNewCanonical(result.suggestion.canonicalName) } @@ -69,6 +72,19 @@ export function Autocomplete({ ); } +function debounce( + func: SuggestionsFetchRequested, + timeout = 1000 +): SuggestionsFetchRequested { + let timer: any; + return (...args) => { + clearTimeout(timer); + timer = setTimeout(() => { + func(...args); + }, timeout); + }; +} + type Request = { query: string; languageCode: string;