Skip to content

Instantly share code, notes, and snippets.

@AntoinePlu
Last active March 10, 2019 12:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AntoinePlu/1a2422dd733c67c54525c845869d607b to your computer and use it in GitHub Desktop.
Save AntoinePlu/1a2422dd733c67c54525c845869d607b to your computer and use it in GitHub Desktop.
import React, { Component } from "react";
import { InstantSearch } from "react-instantsearch-dom";
import qs from 'qs';
import PropTypes from 'prop-types';
import searchClient from "../resources/search";
import ExploreGridContainer from "../component/explore-grid";
import ExploreIntro from "../component/explore-intro";
const DEBOUNCE_TIME = 700;
const createURL = state => {
const routeState = {
query: state.query,
category:
state.refinementList &&
state.refinementList.category &&
state.refinementList.category.join('~'),
page: state.page,
};
return `?${qs.stringify(routeState)}`;
};
const searchStateToUrl = (props, searchState) =>
searchState ? `${props.location.pathname}${createURL(searchState)}` : '';
const urlToSearchState = location => {
const routeState = qs.parse(location.search.slice(1));
const searchState = {
query: routeState.query,
refinementList: {
category: (routeState.category && routeState.category.split('~')) || [],
},
page: routeState.page || 1,
};
return searchState;
};
class ExploreContainer extends Component {
constructor(props) {
super(props);
this.state = {
searchState: urlToSearchState(props.location),
};
}
componentWillReceiveProps(props) {
if (props.location !== this.props.location) {
this.setState({ searchState: urlToSearchState(props.location) });
}
}
onSearchStateChange = searchState => {
clearTimeout(this.debouncedSetState);
this.debouncedSetState = setTimeout(() => {
this.props.history.push(
searchStateToUrl(this.props, searchState),
searchState
);
}, DEBOUNCE_TIME);
this.setState({ searchState });
};
render() {
return (
<InstantSearch
searchClient={searchClient}
indexName="INDEXNAME"
searchState={this.state.searchState}
onSearchStateChange={this.onSearchStateChange}
createURL={createURL}
>
<ExploreIntro />
<ExploreGridContainer />
</InstantSearch>
);
}
}
ExploreContainer.propTypes = {
history: PropTypes.shape({
push: PropTypes.func.isRequired,
}),
location: PropTypes.object.isRequired,
};
export default ExploreContainer;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment