Last active
August 19, 2021 11:32
-
-
Save smashingpat/df50bd2f0a74ba4f72a460abd186b5fd to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as React from 'react'; | |
function useDebouncedValue<T>(value: T, timeout: number) { | |
const [debouncedValue, setDebouncedValue] = React.useState(value); | |
React.useEffect(() => { | |
const id = setTimeout(() => setDebouncedValue(value), timeout); | |
return () => clearTimeout(id); | |
}, [value, timeout]); | |
return debouncedValue; | |
} | |
async function getSeachResults(signal: AbortSignal, query: string) { | |
const response = await fetch(`/api/search?q=${encodeURIComponent(query)}`, { signal ); | |
const data = await response.json(); | |
return data; | |
} | |
export function SearchPage() { | |
const [value, setValue] = React.useState(''); | |
const [results, setResults] = React.useState([]); | |
const debouncedValue = useDebouncedValue(value, 300); | |
React.useEffect(() => { | |
const controller = new AbortController(); | |
getSeachResults(controller.signal, debouncedValue).then(setResults); | |
return () => { | |
controller.abort(); | |
}; | |
}, [debouncedValue]); | |
// render | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment