-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathsearch.js
88 lines (78 loc) · 2.29 KB
/
search.js
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import { useRouter } from 'next/router'
import useSWR, { mutate } from 'swr'
import styled from 'styled-components'
import Skeleton from '@material-ui/lab/Skeleton'
import Typography from '@material-ui/core/Typography'
import { useEffect } from 'react'
import SearchResult from '../components/search/SearchResult'
const fetcher = url => fetch(url).then(r => r.json())
export default function SearchResults() {
const { data, error, isValidating } = useSWR(`${process.env.NEXT_PUBLIC_HCMS_API_URL}/articles`, fetcher, {
revalidateOnFocus: false,
initialData: []
})
const router = useRouter()
const { query } = router
const { searchValue } = query
const filteredData = data.map(result => {
if (
result.title.toLowerCase().includes(searchValue.toLowerCase()) ||
result.content.toLowerCase().includes(searchValue.toLowerCase())
) {
return <SearchResult key={result.id} value={searchValue} result={result} />
}
})
const skeletonArr = [ 1, 2, 3, 4, 5 ]
useEffect(() => {
mutate(`${process.env.NEXT_PUBLIC_HCMS_API_URL}/articles`)
}, [searchValue])
return (
<DivSearchResults>
{
filteredData.every(dataItem => dataItem === undefined)
? <span>No results for "{searchValue}"</span>
: <span>Search results for "{searchValue}" :</span>
}
{!data || isValidating ? (
skeletonArr.map(result => {
return (
<div key={result}>
<Skeleton variant="circle" width={45} height={45} />
<Typography component="div" key="h2" variant="h2">
<Skeleton />
</Typography>
</div>
)
})
) : error ? (
<div>Error</div>
) : (
filteredData
)}
</DivSearchResults>
)
}
const DivSearchResults = styled.div`
grid-area: 2 / 1 / 3 / 2;
justify-self: center;
display: flex;
flex-direction: column;
padding: 1em;
width: 100%;
max-width: 768px;
> :first-child {
margin-bottom: 1em;
}
> div {
display: flex;
> :first-child {
margin: 1em 1em 0 0;
}
> :last-child {
width: 100%;
}
}
@media only screen and (min-width: 1248px) {
grid-area: 2 / 2 / 3 / 3;
}
`