File size: 3,146 Bytes
1e92f2d |
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 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 |
import React from 'react';
import qs from 'qs';
import { useLocation, useHistory } from 'react-router-dom';
import {
InstantSearch,
HierarchicalMenu,
Hits,
Menu,
Pagination,
PoweredBy,
RatingMenu,
RefinementList,
SearchBox,
ClearRefinements,
} from 'react-instantsearch-dom';
import algoliasearch from 'algoliasearch/lite';
const searchClient = algoliasearch(
'latency',
'6be0576ff61c053d5f9a3225e2a90f76'
);
const DEBOUNCE_TIME = 700;
const createURL = (state) => `?${qs.stringify(state)}`;
const searchStateToUrl = (location, searchState) =>
searchState ? `${location.pathname}${createURL(searchState)}` : '';
const urlToSearchState = (location) => qs.parse(location.search.slice(1));
function App() {
const location = useLocation();
const history = useHistory();
const [searchState, setSearchState] = React.useState(
urlToSearchState(location)
);
const setStateId = React.useRef();
React.useEffect(() => {
const nextSearchState = urlToSearchState(location);
if (JSON.stringify(searchState) !== JSON.stringify(nextSearchState)) {
setSearchState(nextSearchState);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [location]);
function onSearchStateChange(nextSearchState) {
clearTimeout(setStateId.current);
setStateId.current = setTimeout(() => {
history.push(
searchStateToUrl(location, nextSearchState),
nextSearchState
);
}, DEBOUNCE_TIME);
setSearchState(nextSearchState);
}
return (
<InstantSearch
searchClient={searchClient}
indexName="instant_search"
searchState={searchState}
onSearchStateChange={onSearchStateChange}
createURL={createURL}
>
<div>
<div
style={{
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
marginBottom: 10,
}}
>
<SearchBox />
<PoweredBy />
</div>
<div style={{ display: 'flex' }}>
<div style={{ padding: '0px 20px' }}>
<p>Hierarchical Menu</p>
<HierarchicalMenu
id="categories"
attributes={[
'hierarchicalCategories.lvl0',
'hierarchicalCategories.lvl1',
'hierarchicalCategories.lvl2',
]}
/>
<p>Menu</p>
<Menu attribute="type" />
<p>Refinement List</p>
<RefinementList attribute="brand" />
<p>Range Ratings</p>
<RatingMenu attribute="rating" max={6} />
</div>
<div style={{ display: 'flex', flexDirection: 'column', flex: 1 }}>
<div style={{ display: 'flex', justifyContent: 'space-around' }}>
<ClearRefinements />
</div>
<div>
<Hits />
</div>
<div style={{ alignSelf: 'center' }}>
<Pagination showLast={true} />
</div>
</div>
</div>
</div>
</InstantSearch>
);
}
export default App;
|