use-query-params
Version:
React Hook for managing state in URL query parameters with easy serialization.
34 lines (33 loc) • 901 B
JavaScript
import { useEffect, useState } from "react";
function makeAdapter({ onChange }) {
const adapter = {
replace(location) {
window.history.replaceState(location.state, "", location.search || "?");
onChange();
},
push(location) {
window.history.pushState(location.state, "", location.search || "?");
onChange();
},
get location() {
return window.location;
}
};
return adapter;
}
const WindowHistoryAdapter = ({
children
}) => {
const handleURLChange = () => setAdapter(makeAdapter({ onChange: handleURLChange }));
const [adapter, setAdapter] = useState(
() => makeAdapter({ onChange: handleURLChange })
);
useEffect(() => {
window.addEventListener("popstate", handleURLChange);
return () => window.removeEventListener("popstate", handleURLChange);
}, []);
return children(adapter);
};
export {
WindowHistoryAdapter
};