wrolpi/app/src/hooks/useSearchParam.js

22 lines
669 B
JavaScript
Raw Normal View History

import {useEffect, useState} from "react";
import {useHistory} from "react-router-dom";
export const useSearchParam = (key, defaultValue = null) => {
// Get a window.location.search param.
const startingValue = new URLSearchParams(window.location.search).get(key);
const [value, setValue] = useState(startingValue || defaultValue);
const history = useHistory();
useEffect(() => {
const params = new URLSearchParams(window.location.search);
params.delete(key);
if (value) {
params.append(key, value);
}
history.push({search: params.toString()});
}, [value])
return [value, setValue];
}