query.js

1.1 kB · javascript · 33 lines

1import { useState } from 'react';23export function share(values) {4  return `?${new URLSearchParams(values)}`;5}67export function stamp(values) {8  const params = new URLSearchParams(location.search);9  for (const [key, value] of Object.entries(values)) {10    if (value === null || value === undefined || value === '' || value === false) params.delete(key);11    else params.set(key, value === true ? 1 : value);12  }13  const tail = String(params);14  history.replaceState(null, '', location.pathname + (tail ? `?${tail}` : ''));15}1617export function useQuery(defaults) {18  const [state, setState] = useState(() => {19    const params = new URLSearchParams(location.search);20    const first = { ...defaults };21    for (const [key, fallback] of Object.entries(defaults)) {22      if (!params.has(key)) continue;23      const raw = params.get(key);24      first[key] = typeof fallback === 'number' ? +raw : typeof fallback === 'boolean' ? raw === '1' : raw;25    }26    return first;27  });28  const set = (patch) => {29    stamp(patch);30    setState((old) => ({ ...old, ...patch }));31  };32  return [state, set];33}