File size: 2,003 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 | import React from 'react';
import { useRouter } from 'next/router';
import qs from 'qs';
import algoliasearch from 'algoliasearch/lite';
import { findResultsState } from 'react-instantsearch-dom/server';
import { Head, App } from '../components';
const searchClient = algoliasearch(
'latency',
'6be0576ff61c053d5f9a3225e2a90f76'
);
const updateAfter = 700;
const createURL = (state) => `?${qs.stringify(state)}`;
const pathToSearchState = (path) =>
path.includes('?') ? qs.parse(path.substring(path.indexOf('?') + 1)) : {};
const searchStateToURL = (searchState) =>
searchState ? `${window.location.pathname}?${qs.stringify(searchState)}` : '';
const DEFAULT_PROPS = {
searchClient,
indexName: 'instant_search',
};
export default function Page(props) {
const [searchState, setSearchState] = React.useState(props.searchState);
const router = useRouter();
const debouncedSetState = React.useRef();
React.useEffect(() => {
if (router) {
router.beforePopState(({ url }) => {
setSearchState(pathToSearchState(url));
});
}
}, [router]);
return (
<div>
<Head title="Home" />
<App
{...DEFAULT_PROPS}
searchState={searchState}
resultsState={props.resultsState}
onSearchStateChange={(nextSearchState) => {
clearTimeout(debouncedSetState.current);
debouncedSetState.current = setTimeout(() => {
const href = searchStateToURL(nextSearchState);
router.push(href, href, { shallow: true });
}, updateAfter);
setSearchState(nextSearchState);
}}
createURL={createURL}
/>
</div>
);
}
export async function getServerSideProps({ resolvedUrl }) {
const searchState = pathToSearchState(resolvedUrl);
const resultsState = await findResultsState(App, {
...DEFAULT_PROPS,
searchState,
});
return {
props: {
resultsState: JSON.parse(JSON.stringify(resultsState)),
searchState,
},
};
}
|