'ReferenceError: window is not defined, when trying to sync the search input state with react instant search [duplicate]
I am using next js and I am trying to sync my search state with url query params, so that during navigation I don't lose my search input state.
I know that it's a sever side language, but what can I do to make this code work with window object?
This is a code snippet from official algolia examples - https://github.com/algolia/react-instantsearch/blob/master/examples/media/URLSync.js
import React, { Component } from "react";
import qs from "qs";
const updateAfter = 700;
const searchStateToURL = (searchState) =>
searchState ? `${window.location.pathname}?${qs.stringify(searchState)}` : "";
const withURLSync = (TestSearch) =>
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 (
<TestSearch
{...this.props}
searchState={searchState}
onSearchStateChange={this.onSearchStateChange}
createURL={searchStateToURL}
/>
);
}
};
export default withURLSync;
It works with react js, but how can I make this code snippet work with next.js?
Solution 1:[1]
You should put everything that uses window under an if statement that checks whether the code is running client side or server side.
For example create a function like this:
export const isClient = () => !(typeof window === "undefined");
Or just a variable:
export const isClient = !(typeof window === "undefined");
And in your case you can do like this (using the variable one):
componentDidMount() {
if(isClient) {
window.addEventListener("popstate", this.onPopState);
}
}
This way you make sure that whenever your code runs window is not undefined
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | alisei_ |
