Skip to content
This repository has been archived by the owner on Mar 15, 2023. It is now read-only.

Commit

Permalink
Step 4: Creating a search API to make dynamic queries in the app
Browse files Browse the repository at this point in the history
  • Loading branch information
colbyfayock committed Dec 28, 2022
1 parent 58772ee commit 8d9c971
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
17 changes: 17 additions & 0 deletions 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)
});
}
22 changes: 21 additions & 1 deletion src/pages/index.js
Expand Up @@ -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
*/
Expand Down Expand Up @@ -87,7 +107,7 @@ export default function Home({ products, categories }) {
<h2 className="sr-only">Products</h2>

<ul className={styles.products}>
{products.map(product => {
{activeProducts.map(product => {
return (
<li key={product.id}>
<a className={styles.productImageWrapper} href={product.productUrl} rel="noopener noreferrer">
Expand Down

0 comments on commit 8d9c971

Please sign in to comment.