0

I need to write an hook that fetch the URL query parameters to return an object of strictly type T

export function useQueryParams<T>(): [
  T,
  ({ key, value }: { key: keyof T; value: string }) => void,
] {
  const [searchParams, setSearchParams] = useSearchParams()
  const entries = Array.from(searchParams.entries()).reduce(
    (acc, [key, value]) => {
      return { ...acc, [key]: value }
    },
    {} as T,
  )

  const setQueryParam = React.useCallback(
    ({ key, value }) => {
      searchParams.set(key, value)
      setSearchParams(searchParams)
    },
    [searchParams, setSearchParams],
  )

  return [entries, setQueryParam]
}

The problem of the above code is that it doesn't throw an error when the URL contains more parameters that are not part of T. The problem is the reduce function that return an object of type Partial<T> bypassing the check for the return type of the hook. How can I reduce correctly searchParams.entries() to get an object of type T containing exactly its properties?

EDIT: minimal reproducible example

  • please provide reproducible example with imports – captain-yossarian from Ukraine Jun 13 '22 at 08:59
  • Your [mre] should be included as plaintext in the body of the question; an external link is a great supplement, but doesn't take the place of having everything needed in the question itself. We can't require that someone navigate away from Stack Overflow in order to see the code relevant to the question. Also it's helpful for you to try to minimize the example without dependencies on too much third-party stuff; if you can disentangle your question from react, for example, then more people can help you. – jcalz Jun 13 '22 at 13:09

0 Answers0