Skip to content

Instantly share code, notes, and snippets.

@AntoinePlu
Created March 10, 2019 12:36
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/d639d0f31b532d2c6dfccdb6dda55af3 to your computer and use it in GitHub Desktop.
Save AntoinePlu/d639d0f31b532d2c6dfccdb6dda55af3 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 updateAfter = 300;
const createURL = state => `?${qs.stringify(state)}`;
const searchStateToUrl = (props, searchState) =>
searchState ? `${props.location.pathname}${createURL(searchState)}` : '';
const urlToSearchState = location => qs.parse(location.search.slice(1));
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
);
}, updateAfter);
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