diff --git a/src/pages/api/search.js b/src/pages/api/search.js new file mode 100644 index 0000000..f36fd73 --- /dev/null +++ b/src/pages/api/search.js @@ -0,0 +1,17 @@ +import { getXataClient } from 'src/lib/xata'; + +const xata = getXataClient(); + +export default async function handler(req, res) { + const { query } = JSON.parse(req.body); + + const records = await xata.search.all(query, { + tables: [{ table: 'products' }], + fuzziness: 0, + prefix: 'phrase', + }); + + res.status(200).json({ + products: records.map(({ record }) => record) + }); +} \ No newline at end of file diff --git a/src/pages/index.js b/src/pages/index.js index 943023a..35b55c9 100644 --- a/src/pages/index.js +++ b/src/pages/index.js @@ -15,12 +15,32 @@ import styles from '@styles/Home.module.scss'; export default function Home({ products, categories }) { const [searchQuery, setSearchQuery] = useState(); const [searchCategory, setSearchCategory] = useState(); + const [searchResults, setSearchResults] = useState(); + + const activeProducts = searchQuery?.length && searchResults ? searchResults : products; // Add debouncing when setting query state to avoid making quick, repetitive // requests for every single letter typed const debouncedSetSearchQuery = useDebouncedCallback((value) => setSearchQuery(value), 500); + useEffect(() => { + if ( !searchQuery ) { + setSearchResults(undefined); + return; + }; + + (async function run() { + const { products } = await fetch('/api/search', { + method: 'POST', + body: JSON.stringify({ + query: searchQuery + }) + }).then(r => r.json()); + setSearchResults(products); + })(); + }, [searchQuery]); + /** * handleOnSearch */ @@ -87,7 +107,7 @@ export default function Home({ products, categories }) {

Products