I have a bunch of books that I just want to be able to search a title and see the description with pagination. The books are in an astrodb and I have it working to where I can query and show them manually. However, I am trying to get a UI search working and am a little lost.
When I edit the url directly to http://localhost:4321/?query=booktitle I am able to load a search, however, I am trying to get this to work with some sort of input on the UI side now. I tried using an <input> an onupdate or an onclick with a <button> next to the input, but am not sure best practices for loading a search. Any help for this learning newbie is appreciated! Thank you!
/src/index.astro
---
import { GET } from '../api/search.ts'
const response = await GET(Astro)
const data = await response.json()
console.log(data.books)
interface Book {
title: string
description: string
}
const books: Book[] = data.books
---
<h2>Website loaded</h2>
<input
type="text"
placeholder="Search..."
/>
{
books.map(({ title, description }) => (
<div>
<p>{title}</p>
<p>{description}</p>
</div>
))
}
/src/api/search.ts
import type { APIRoute } from 'astro';
import { searchBooks } from '../search';
export const GET: APIRoute = async (context) => {
const query = context.url.searchParams.get('query') || '';
const sortby = 'asc';
const page = 0;
const resultsPerPage = 4;
const foundBooks = await searchBooks(query, sortby, page, resultsPerPage);
return new Response(
JSON.stringify({
books: foundBooks,
}),
{
headers: { 'content-type': 'application/json' }
}
)
}