UNPKG

982 BJavaScriptView Raw
1import { useEffect } from 'react';
2
3export const getSearchParam = (parameter = '', location = window.location) => {
4 const params = new URLSearchParams(location.search);
5
6 return params.get(parameter) || '';
7};
8
9/**
10 * A [React Hook]{@link https://reactjs.org/docs/hooks-intro.html} that gets
11 * a search parameter from a URL and calls a provided setter function with
12 * the corresponding value.
13 *
14 * @kind function
15 *
16 * @param {Object} props An object containing the location, parameter, and setter function.
17 * @param {String} props.location The URL location to search in
18 * @param {String} props.parameter The parameter to search for
19 * @param {Function} props.setValue A setter function that is passed the parameter value found in the URL
20 */
21export const useSearchParam = props => {
22 const { location, parameter, setValue } = props;
23 const value = getSearchParam(parameter, location);
24
25 useEffect(() => {
26 setValue(value);
27 }, [setValue, value]);
28};