Skip to content

Commit

Permalink
Algolia result list pattern (#8)
Browse files Browse the repository at this point in the history
  • Loading branch information
pookmish authored May 7, 2024
1 parent fee93cf commit a42f27f
Showing 1 changed file with 89 additions and 0 deletions.
89 changes: 89 additions & 0 deletions src/components/patterns/algolia-course-list.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
"use client";

import algoliasearch from "algoliasearch/lite";
import {useHits,usePagination, Configure} from "react-instantsearch";
import {InstantSearchNext} from "react-instantsearch-nextjs";
import {useMemo} from "react";
import {Hit as HitType} from "instantsearch.js";

type Props = {
appId: string
searchIndex: string
searchApiKey: string
itemUuids: string[]
}

const AlgoliaCourseList = ({appId, searchIndex, searchApiKey, itemUuids}: Props) => {
const searchClient = useMemo(() => algoliasearch(appId, searchApiKey), [appId, searchApiKey])
return (
<InstantSearchNext
indexName={searchIndex}
searchClient={searchClient}
future={{preserveSharedStateOnUnmount: true}}
>
<Configure
filters={itemUuids.map(uuid => `objectID:'${uuid}'`).join(" OR ")}
attributesToHighlight={["html"]}
attributesToSnippet={["html"]}
/>
<HitList/>
</InstantSearchNext>
)
}

const HitList = () => {
const {hits} = useHits<HitType>({});
const {currentRefinement: currentPage, pages, nbPages, refine: goToPage} = usePagination({padding: 2})

if (hits.length === 0) {
return (
<p>No favorites at this time.</p>
)
}

return (
<div>
<ul className="list-unstyled">
{hits.map(hit =>
<li key={hit.objectID} className="border-b border-gray-300 last:border-0">
<div>
{hit.title}
</div>
</li>
)}
</ul>

{pages.length > 1 &&
<nav aria-label="Search results pager">
<ul className="list-unstyled flex justify-between">
{pages[0] > 0 &&
<li>
<button onClick={() => goToPage(0)}>
First
</button>
</li>
}

{pages.map(pageNum =>
<li key={`page-${pageNum}`} aria-current={currentPage === pageNum}>
<button onClick={() => goToPage(pageNum)}>
{pageNum + 1}
</button>
</li>
)}

{pages[pages.length - 1] !== nbPages &&
<li>
<button onClick={() => goToPage(nbPages - 1)}>
Last
</button>
</li>
}
</ul>
</nav>
}
</div>
)
}

export default AlgoliaCourseList;

0 comments on commit a42f27f

Please sign in to comment.