0.1.7 • Published 2 years ago

use-sync-query-params v0.1.7

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

use-sync-query-params

Sync React props/states to URL query params.

Purposes

  • Initialize the URL query params with default ones.
    • The default params can come from any source: redux, props, computed variables...
  • Update query params on demand

Installation

  • Using npm
npm install --save use-sync-query-params
  • Using yarn
yarn add use-sync-query-params

Usage examples

import useSyncQueryParams from 'use-sync-query-params'

export default function App(props) {
  const params = useSyncQueryParams({ foo: 'bar' })
  // Or
  const params = useSyncQueryParams({ foo: props.foo })
  // Or
  const foo = new URLSearchParams(window.location.search).get('foo')
  const params = useSyncQueryParams({ foo })

  return (
    <>
      <p>{params.getParam('foo')}</p>
      <p>{window.location.search}</p>
      <pre>{JSON.stringify(params.getAllParams())}</pre>
      <br/>
      <button onClick={() => params.setParam('foo', 'baz')}>Change bar to baz</button>
      <br/>
      <button onClick={() => params.clearParam('foo')}>Clear query param</button>
    </>
  )
}

Demo

APIs

  1. useSyncQueryParams(defaultParams: { [x: string]: string | number | boolean | null | undefined }) => ({ getParam, getAllParams, setParam, setParams, clearParam })

    Initial the hook with default params. Automatic URL query params synchronization will happen only once on mount.

  2. getParam: (key: string) => string

    Get specific key from query params. Autosuggestion mapped to keys of the default params.

  3. getParams: (...keys: string[]) => Object<string, string>

    Get a set of params.

  4. getAllParams: () => Object

    Get all query params. The result contains all records with keys of the default params except those that were cleared.

  5. setParam: (key: string, value: string | number | boolean | null | undefined) => boolean

    Set a specific key with a value. Empty values (empty string, null, undefined) will be cleared.

    • Return true if successfully set
    • Otherwise false if window.history.pushState is not available
  6. setParams: (Object<key: string, value: string | number | boolean | null | undefined>) => boolean

    Set a set of records. Empty values (empty string, null, undefined) will be cleared.

    • Return true if successfully set
    • Otherwise false if window.history.pushState is not available
  7. clearParam: (key: string) => boolean

    Clear specific key from query params. Same as setParam with empty value.

  8. clearParams: (...keys: string[]) => boolean

    Clear a set of keys from query params. Same as setParams with empty values.

0.1.7

2 years ago

0.1.4

2 years ago

0.1.6

2 years ago

0.1.5

2 years ago

0.1.3

2 years ago

0.1.2

2 years ago

0.1.1

2 years ago

0.1.0

2 years ago