useQuery

Hooks for react-router query parameters.

Source code is hosted on GitHub

yarn add @corets/use-query

useQuery()

Read and update URL query from your React component:

import React from "react"
import { useQuery } from "@corets/use-query"

const Example = () => {
  const [query, setQuery, patchQuery] = useQuery({
    page: 1,
    order: "asc"
  })
  
  // update page and also reset order to the initial value "asc"
  const handleGoToNextPage = () => setQuery({ page: query.page + 1 })
  
  // update order, but keep page as is
  const handleToggleSort = () => patchQuery({ order: query.order === "asc" ? "desc" : "asc" })
  
  return (
    <div>
      <div>Page: {query.page}</div>
      <div>Order: {query.order}</div>
      <button onClick={handleGoToNextPage}>Go to next page</button>
      <button onClick={handleToggleSort}>Change sorting order</button>
    </div>
  )
}

By default, parameters like "", null, undefined, 0 and "0" are stripped, the default value will be used instead. Updating the query with one of those values won't change anything. You can alter this behavior by providing a second argument, overriding values that should be stripped away:

useQuery({ some: "value" }, ["", null, undefined])

Last updated