forked from vercel/commerce
-
Notifications
You must be signed in to change notification settings - Fork 0
/
search.tsx
52 lines (41 loc) · 1.36 KB
/
search.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import { useEffect, useState } from 'react'
import getSlug from './get-slug'
export function useSearchMeta(asPath: string) {
const [pathname, setPathname] = useState<string>('/search')
const [category, setCategory] = useState<string | undefined>()
const [brand, setBrand] = useState<string | undefined>()
useEffect(() => {
// Only access asPath after hydration to avoid a server mismatch
const path = asPath.split('?')[0]
const parts = path.split('/')
let c = parts[2]
let b = parts[3]
if (c === 'designers') {
c = parts[4]
}
setPathname(path)
if (c !== category) setCategory(c)
if (b !== brand) setBrand(b)
}, [asPath])
return { pathname, category, brand }
}
// Removes empty query parameters from the query object
export const filterQuery = (query: any) =>
Object.keys(query).reduce<any>((obj, key) => {
if (query[key]?.length) {
obj[key] = query[key]
}
return obj
}, {})
export const getCategoryPath = (path: string, brand?: string) => {
const category = getSlug(path)
return `/search${brand ? `/designers/${brand}` : ''}${
category ? `/${category}` : ''
}`
}
export const getDesignerPath = (path: string, category?: string) => {
const designer = getSlug(path).replace(/^brands/, 'designers')
return `/search${designer ? `/${designer}` : ''}${
category ? `/${category}` : ''
}`
}