|
1
|
"use client" |
|
2
|
|
|
3
|
import { usePathname } from "next/navigation" |
|
4
|
import { useSearch } from "../../providers/Search" |
|
5
|
import { useEffect, useState } from "react" |
|
6
|
import { HitType } from "../../components" |
|
7
|
|
|
8
|
type SimilarPage = { |
|
9
|
id: string |
|
10
|
title: string |
|
11
|
url: string |
|
12
|
} |
|
13
|
|
|
14
|
export const useSimilarPages = () => { |
|
15
|
const pathname = usePathname() |
|
16
|
const { searchClient, selectedIndex } = useSearch() |
|
17
|
const [similarPages, setSimilarPages] = useState<SimilarPage[]>([]) |
|
18
|
|
|
19
|
useEffect(() => { |
|
20
|
void searchClient |
|
21
|
.search<HitType>({ |
|
22
|
requests: [ |
|
23
|
{ |
|
24
|
query: pathname.split("/").join(" ").trim(), |
|
25
|
indexName: selectedIndex, |
|
26
|
hitsPerPage: 3, |
|
27
|
distinct: true, |
|
28
|
}, |
|
29
|
], |
|
30
|
}) |
|
31
|
.then(({ results }) => { |
|
32
|
const hits = "hits" in results[0] ? results[0].hits : [] |
|
33
|
const pages = hits.map((hit) => ({ |
|
34
|
id: hit.objectID, |
|
35
|
title: hit.hierarchy.lvl1 || hit.hierarchy.lvl0 || "Untitled", |
|
36
|
url: hit.url, |
|
37
|
})) |
|
38
|
setSimilarPages(pages) |
|
39
|
}) |
|
40
|
.catch(() => { |
|
41
|
setSimilarPages([]) |
|
42
|
}) |
|
43
|
}, [pathname, searchClient]) |
|
44
|
|
|
45
|
return similarPages |
|
46
|
} |