File size: 1,339 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 |
import React, { Component } from 'react';
import qs from 'qs';
const updateAfter = 700;
const searchStateToURL = (searchState) =>
searchState ? `${window.location.pathname}?${qs.stringify(searchState)}` : '';
const withURLSync = (App) =>
class WithURLSync extends Component {
state = {
searchState: qs.parse(window.location.search.slice(1)),
};
componentDidMount() {
window.addEventListener('popstate', this.onPopState);
}
componentWillUnmount() {
clearTimeout(this.debouncedSetState);
window.removeEventListener('popstate', this.onPopState);
}
onPopState = ({ state }) =>
this.setState({
searchState: state || {},
});
onSearchStateChange = (searchState) => {
clearTimeout(this.debouncedSetState);
this.debouncedSetState = setTimeout(() => {
window.history.pushState(
searchState,
null,
searchStateToURL(searchState)
);
}, updateAfter);
this.setState({ searchState });
};
render() {
const { searchState } = this.state;
return (
<App
{...this.props}
searchState={searchState}
onSearchStateChange={this.onSearchStateChange}
createURL={searchStateToURL}
/>
);
}
};
export default withURLSync;
|