Skip to content

Instantly share code, notes, and snippets.

@luxcem
Last active April 4, 2019 12:41
Show Gist options
  • Save luxcem/497ebdefda439c9fceeecdd830ef4ec1 to your computer and use it in GitHub Desktop.
Save luxcem/497ebdefda439c9fceeecdd830ef4ec1 to your computer and use it in GitHub Desktop.
Example of a React custom hooks for searching an api.
import axios from "axios";
import { useState } from "react";
import { useDebouncedCallback } from "use-debounce";
function useSearch() {
const [value, setValue] = useState("");
const [results, setResults] = useState([]);
const [debouncedCallback] = useDebouncedCallback(value => {
axios.get("/s/?q=" + value).then(res => {
setResults(res.data.map(e => e.ref));
});
}, 300);
function onChange(value) {
setValue(value);
debouncedCallback(value);
}
return [value, results, onChange];
}
// Usage
function SearchBar() {
const [query, results, setQuery] = useSearch();
return (
<div>
<input
type="text"
placeholder="Search"
value={query}
onChange={e => setQuery(e.target.value)}
/>
{results.length > 0 && (
<div>
{results.map(e => <a href={e}>{e}</a>))}
</div>
)}
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment