-
-
Save AntoinePlu/5b08a606297eee69b99b4b954d8ccf21 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, | |
type: | |
state.menu && | |
state.menu.type && | |
state.menu.type.join('~'), | |
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, | |
menu: { | |
type: (routeState.type && routeState.type.split('~')) || [], | |
}, | |
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