All Projects → pbeshai → Use Query Params

pbeshai / Use Query Params

Licence: isc
React Hook for managing state in URL query parameters with easy serialization.

Programming Languages

typescript
32286 projects

Projects that are alternatives of or similar to Use Query Params

URLQueryItemEncoder
A Swift Encoder for encoding any Encodable value into an array of URLQueryItem.
Stars: ✭ 60 (-95.31%)
Mutual labels:  url, query
go-qs
A Go port of Rack's query string parser
Stars: ✭ 96 (-92.49%)
Mutual labels:  url, query
uri-query-parser
a parser and a builder to work with URI query string the right way in PHP
Stars: ✭ 38 (-97.03%)
Mutual labels:  url, query
React Query
⚛️ Hooks for fetching, caching and updating asynchronous data in React
Stars: ✭ 24,427 (+1811.35%)
Mutual labels:  hooks, query
React Selector Hooks
Collection of hook-based memoized selector factories for declarations outside of render.
Stars: ✭ 84 (-93.43%)
Mutual labels:  hooks
Firegraph
GraphQL Superpowers for Google Cloud Firestore
Stars: ✭ 80 (-93.74%)
Mutual labels:  query
Redmine issues tree
Provides a tree view of the Redmine issues list
Stars: ✭ 79 (-93.82%)
Mutual labels:  hooks
Pumpkindb
Immutable Ordered Key-Value Database Engine
Stars: ✭ 1,219 (-4.62%)
Mutual labels:  query
Postinstall Build
Helper for conditionally building your npm package on postinstall
Stars: ✭ 87 (-93.19%)
Mutual labels:  hooks
Libvmod Querystring
Query-string module for Varnish Cache
Stars: ✭ 85 (-93.35%)
Mutual labels:  url
Hpq
Utility to parse and query HTML into an object shape
Stars: ✭ 82 (-93.58%)
Mutual labels:  query
D3blackbox
A simple React wrapper for any D3 code you want
Stars: ✭ 80 (-93.74%)
Mutual labels:  hooks
React Ufo
🛸 react-ufo - A simple React hook to help you with data fetching 🛸
Stars: ✭ 85 (-93.35%)
Mutual labels:  hooks
Laravel Url Shortener
Powerful URL shortening tools in Laravel
Stars: ✭ 80 (-93.74%)
Mutual labels:  url
Autocomplete
🔮 Fast and full-featured autocomplete library
Stars: ✭ 1,268 (-0.78%)
Mutual labels:  query
Askxml
Run SQL statements on XML documents
Stars: ✭ 79 (-93.82%)
Mutual labels:  query
Pwa Boilerplate
✨ PWA Boilerplate is highly scalable and is designed to help you kick-start your next project 🔭.
Stars: ✭ 82 (-93.58%)
Mutual labels:  hooks
Urlpages
Create and view web pages stored entirely in the URL
Stars: ✭ 1,263 (-1.17%)
Mutual labels:  url
Gitio.fish
Create a custom git.io URL.
Stars: ✭ 81 (-93.66%)
Mutual labels:  url
Write With Me
Real-time Collaborative Markdown Editor
Stars: ✭ 81 (-93.66%)
Mutual labels:  hooks

useQueryParams

A React Hook, HOC, and Render Props solution for managing state in URL query parameters with easy serialization.

Works with React Router and Reach Router out of the box. TypeScript supported.

npm Travis (.com)


Installation | Usage | Examples | API | Demo


When creating apps with easily shareable URLs, you often want to encode state as query parameters, but all query parameters must be encoded as strings. useQueryParams allows you to easily encode and decode data of any type as query parameters with smart memoization to prevent creating unnecessary duplicate objects. It uses serialize-query-params.

Installation

Using npm:

$ npm install --save use-query-params query-string

Note: There is a peer dependency on query-string. For IE11 support, use v5.1.1, otherwise use v6.

Link your routing system (e.g., React Router example, Reach Router example):

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import { QueryParamProvider } from 'use-query-params';
import App from './App';

ReactDOM.render(
  <Router>
    <QueryParamProvider ReactRouterRoute={Route}>
      <App />
    </QueryParamProvider>
  </Router>,
  document.getElementById('root')
);

Usage

Be sure to add QueryParamProvider as shown in Installation above.

Add the hook to your component. There are two options: useQueryParam:

import * as React from 'react';
import { useQueryParam, NumberParam, StringParam } from 'use-query-params';

const UseQueryParamExample = () => {
  // something like: ?x=123&foo=bar in the URL
  const [num, setNum] = useQueryParam('x', NumberParam);
  const [foo, setFoo] = useQueryParam('foo', StringParam);

  return (
    <div>
      <h1>num is {num}</h1>
      <button onClick={() => setNum(Math.random())}>Change</button>
      <h1>foo is {foo}</h1>
      <button onClick={() => setFoo(`str${Math.random()}`)}>Change</button>
    </div>
  );
};

export default UseQueryParamExample;

Or useQueryParams:

import * as React from 'react';
import {
  useQueryParams,
  StringParam,
  NumberParam,
  ArrayParam,
  withDefault,
} from 'use-query-params';

const UseQueryParamsExample = () => {
  // something like: ?x=123&q=foo&filters=a&filters=b&filters=c in the URL
  const [query, setQuery] = useQueryParams({
    x: NumberParam,
    q: StringParam,
    filters: withDefault(ArrayParam, []),
  });
  const { x: num, q: searchQuery, filters } = query;

  return (
    <div>
      <h1>num is {num}</h1>
      <button onClick={() => setQuery({ x: Math.random() })}>Change</button>
      <h1>searchQuery is {searchQuery}</h1>
      <h1>There are {filters.length} filters active.</h1>
      <button
        onClick={() =>
          setQuery(
            { x: Math.random(), filters: [...filters, 'foo'], q: 'bar' },
            'push'
          )
        }
      >
        Change All
      </button>
    </div>
  );
};

export default UseQueryParamsExample;

Or with the higher-order component (HOC) withQueryParams:

import * as React from 'react';
import {
  withQueryParams,
  StringParam,
  NumberParam,
  ArrayParam,
  withDefault,
} from 'use-query-params';

const WithQueryParamsExample = ({ query, setQuery }: any) => {
  const { x: num, q: searchQuery, filters } = query;

  return (
    <div>
      <h1>num is {num}</h1>
      <button onClick={() => setQuery({ x: Math.random() })}>Change</button>
      <h1>searchQuery is {searchQuery}</h1>
      <h1>There are {filters.length} filters active.</h1>
      <button
        onClick={() =>
          setQuery(
            { x: Math.random(), filters: [...filters, 'foo'], q: 'bar' },
            'push'
          )
        }
      >
        Change All
      </button>
    </div>
  );
};

export default withQueryParams({
  x: NumberParam,
  q: StringParam,
  filters: withDefault(ArrayParam, []),
}, WithQueryParamsExample);

Or with render props via <QueryParams>:

import * as React from 'react';
import {
  QueryParams,
  StringParam,
  NumberParam,
  ArrayParam,
  withDefault,
} from 'use-query-params';

const RenderPropsExample = () => {
  const queryConfig = {
    x: NumberParam,
    q: StringParam,
    filters: withDefault(ArrayParam, []),
  };
  return (
    <div>
      <QueryParams config={queryConfig}>
        {({ query, setQuery }) => {
          const { x: num, q: searchQuery, filters } = query;
          return (
            <>
              <h1>num is {num}</h1>
              <button onClick={() => setQuery({ x: Math.random() })}>
                Change
              </button>
              <h1>searchQuery is {searchQuery}</h1>
              <h1>There are {filters.length} filters active.</h1>
              <button
                onClick={() =>
                  setQuery(
                    {
                      x: Math.random(),
                      filters: [...filters, 'foo'],
                      q: 'bar',
                    },
                    'push'
                  )
                }
              >
                Change All
              </button>
            </>
          );
        }}
      </QueryParams>
    </div>
  );
};

export default RenderPropsExample;

Examples

A few basic examples have been put together to demonstrate how useQueryParams works with different routing systems.

The React Router and Reach Router examples contain simple tests showing how to use the library with React Testing Library.

API

For convenience, use-query-params exports all of the serialize-query-params library.

UrlUpdateType

The UrlUpdateType is a string type definings the different methods for updating the URL:

  • 'pushIn': Push just a single parameter, leaving the rest as is (back button works) (the default)
  • 'push': Push all parameters with just those specified (back button works)
  • 'replaceIn': Replace just a single parameter, leaving the rest as is
  • 'replace': Replace all parameters with just those specified

Param Types

See all param definitions from serialize-query-params here. You can define your own parameter types by creating an object with an encode and a decode function. See the existing definitions for examples.

Note that all null and empty values are typically treated as follows:

value encoding
null ?qp
"" ?qp=
undefined ? (removed from URL)

Examples in this table assume query parameter named qp.

Param Type Example Decoded Example Encoded
StringParam string 'foo' ?qp=foo
NumberParam number 123 ?qp=123
ObjectParam { key: string } { foo: 'bar', baz: 'zzz' } ?qp=foo-bar_baz-zzz
ArrayParam string[] ['a','b','c'] ?qp=a&qp=b&qp=c
JsonParam any { foo: 'bar' } ?qp=%7B%22foo%22%3A%22bar%22%7D
DateParam Date Date(2019, 2, 1) ?qp=2019-03-01
BooleanParam boolean true ?qp=1
NumericObjectParam { key: number } { foo: 1, bar: 2 } ?qp=foo-1_bar-2
DelimitedArrayParam string[] ['a','b','c'] ?qp=a_b_c
DelimitedNumericArrayParam number[] [1, 2, 3] ?qp=1_2_3

Example

import { ArrayParam, useQueryParam, useQueryParams } from 'use-query-params';

// typically used with the hooks:
const [foo, setFoo] = useQueryParam('foo', ArrayParam);
// - OR -
const [query, setQuery] = useQueryParams({ foo: ArrayParam });

Example with Custom Param

You can define your own params if the ones shipped with this package don't work for you. There are included serialization utility functions to make this easier, but you can use whatever you like.

import {
  encodeDelimitedArray,
  decodeDelimitedArray
} from 'use-query-params';

/** Uses a comma to delimit entries. e.g. ['a', 'b'] => qp?=a,b */
const CommaArrayParam = {
  encode: (array: string[] | null | undefined) =>
    encodeDelimitedArray(array, ','),

  decode: (arrayStr: string | string[] | null | undefined) =>
    decodeDelimitedArray(arrayStr, ',')
};

useQueryParam

useQueryParam<T>(name: string, paramConfig: QueryParamConfig<T>, rawQuery?: ParsedQuery):
  [T | undefined, (newValue: T, updateType?: UrlUpdateType) => void]

Given a query param name and query parameter configuration { encode, decode } return the decoded value and a setter for updating it.

The setter takes two arguments (newValue, updateType) where updateType is one of 'pushIn' | 'push' | 'replaceIn' | 'replace', defaulting to 'pushIn'.

You may optionally pass in a rawQuery object, otherwise the query is derived from the location in the context.

Example

import { useQueryParam, NumberParam } from 'use-query-params';

// reads query parameter `foo` from the URL and stores its decoded numeric value
const [foo, setFoo] = useQueryParam('foo', NumberParam);
setFoo(500);
setFoo(123, 'push');

// to unset or remove a parameter set it to undefined and use pushIn or replaceIn update types
setFoo(undefined) // ?foo=123&bar=zzz becomes ?bar=zzz

// functional updates are also supported:
setFoo((latestFoo) => latestFoo + 150)

useQueryParams

useQueryParams<QPCMap extends QueryParamConfigMap>(paramConfigMap: QPCMap):
  [DecodedValueMap<QPCMap>, SetQuery<QPCMap>]

Given a query parameter configuration (mapping query param name to { encode, decode }), return an object with the decoded values and a setter for updating them.

The setter takes two arguments (newQuery, updateType) where updateType is one of 'pushIn' | 'push' | 'replaceIn' | 'replace', defaulting to 'pushIn'.

Example

import { useQueryParams, StringParam, NumberParam } from 'use-query-params';

// reads query parameters `foo` and `bar` from the URL and stores their decoded values
const [query, setQuery] = useQueryParams({ foo: NumberParam, bar: StringParam });
setQuery({ foo: 500 })
setQuery({ foo: 123, bar: 'zzz' }, 'push');

// to unset or remove a parameter set it to undefined and use pushIn or replaceIn update types
setQuery({ foo: undefined }) // ?foo=123&bar=zzz becomes ?bar=zzz

// functional updates are also supported:
setQuery((latestQuery) => ({ foo: latestQuery.foo + 150 }))

Example with Custom Parameter Type Parameter types are just objects with { encode, decode } functions. You can provide your own if the provided ones don't work for your use case.

import { useQueryParams } from 'use-query-params';

const MyParam = {
  encode(value) {
    return `${value * 10000}`;
  },

  decode(strValue) {
    return parseFloat(strValue) / 10000;
  }
}

// ?foo=10000 -> query = { foo: 1 }
const [query, setQuery] = useQueryParams({ foo: MyParam });

// goes to ?foo=99000
setQuery({ foo: 99 })

withQueryParams

withQueryParams<QPCMap extends QueryParamConfigMap, P extends InjectedQueryProps<QPCMap>>
  (paramConfigMap: QPCMap, WrappedComponent: React.ComponentType<P>):
      React.FC<Diff<P, InjectedQueryProps<QPCMap>>>

Given a query parameter configuration (mapping query param name to { encode, decode }) and a component, inject the props query and setQuery into the component based on the config.

The setter takes two arguments (newQuery, updateType) where updateType is one of 'pushIn' | 'push' | 'replaceIn' | 'replace', defaulting to 'pushIn'.

Example

import { withQueryParams, StringParam, NumberParam } from 'use-query-params';

const MyComponent = ({ query, setQuery, ...others }) => {
  const { foo, bar } = query;
  return <div>foo = {foo}, bar = {bar}</div>
}

// reads query parameters `foo` and `bar` from the URL and stores their decoded values
export default withQueryParams({ foo: NumberParam, bar: StringParam }, MyComponent);

Note there is also a variant called withQueryParamsMapped that allows you to do a react-redux style mapStateToProps equivalent. See the code or this example for details.


QueryParams

<QueryParams config={{ foo: NumberParam }}>
  {({ query, setQuery }) => <div>foo = {query.foo}</div>}
</QueryParams>

Given a query parameter configuration (mapping query param name to { encode, decode }) and a component, provide render props query and setQuery based on the config.

The setter takes two arguments (newQuery, updateType) where updateType is one of 'pushIn' | 'push' | 'replaceIn' | 'replace', defaulting to 'pushIn'.


encodeQueryParams

encodeQueryParams<QPCMap extends QueryParamConfigMap>(
  paramConfigMap: QPCMap,
  query: Partial<DecodedValueMap<QPCMap>>
): EncodedQueryWithNulls

Convert the values in query to strings via the encode functions configured in paramConfigMap. This can be useful for constructing links using decoded query parameters.

Example

import { encodeQueryParams, NumberParam } from 'use-query-params';
// since v1.0 stringify is not exported from 'use-query-params',
// so you must install the 'query-string' package in case you need it
import { stringify } from 'query-string';

// encode each parameter according to the configuration
const encodedQuery = encodeQueryParams({ foo: NumberParam }, { foo });
const link = `/?${stringify(encodedQuery)}`;

QueryParamProvider

// Use one of these:
<QueryParamProvider ReactRouterRoute={Route}><App /></QueryParamProvider>

<QueryParamProvider reachHistory={globalHistory}><App /></QueryParamProvider>

<QueryParamProvider history={myCustomHistory}><App /></QueryParamProvider>

// optionally specify options to query-string stringify
const stringifyOptions = { encode: false }
<QueryParamProvider ReactRouterRoute={Route} stringifyOptions={stringifyOptions}>
  <App />
</QueryParamProvider>

// also accepts a transformSearchString function (searchString: string) => string
import {
  ExtendedStringifyOptions,
  transformSearchStringJsonSafe,
} from 'use-query-params';

const stringifyOptions: ExtendedStringifyOptions = {
  transformSearchString: transformSearchStringJsonSafe,
};
<QueryParamProvider ReactRouterRoute={Route} stringifyOptions={stringifyOptions}>
  <App />
</QueryParamProvider>

The QueryParamProvider component links your routing library's history to the useQueryParams hook. It is needed for the hook to be able to update the URL and have the rest of your app know about it.

See the tests or these examples for how to use it:

Example (Reach Router)

import React from 'react';
import ReactDOM from 'react-dom';
import { globalHistory, Router } from '@reach/router';
import { QueryParamProvider } from 'use-query-params';
import App from './App';

ReactDOM.render(
  <QueryParamProvider reachHistory={globalHistory}>
    <Router>
      <App default />
    </Router>
  </QueryParamProvider>,
  document.getElementById('root')
);

Development

Run the typescript compiler in watch mode:

npm run dev

You can run an example app:

npm link
cd examples/react-router
npm install
npm link use-query-params
npm start
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].