use-query-param
TypeScript icon, indicating that this package has built-in type declarations

1.0.9 • Public • Published

Use Query Param

CircleCI Maintainability JavaScript Style Guide NPM Total Download

A React Hook that extracts query params from a URL query string and returns a queried object.

Published Built With

Installation

npm install use-query-param

Usage

import { useQueryParam, getQueryParams, setQueryParams } from 'use-query-param';

Case One:

Importing module into file
import { useQueryParam } from 'use-query-param';
 
OR
 
const { useQueryParam } = require('use-query-param');

Without an argument

import { useEffect } from 'react'; 
 
const Component = () => {
  const { queryParams } = useQueryParam(); // <== HOOK
 
  useEffect(() => {
      console.log(queryParams);
      // result will be an object of query params
  }, [queryParams])
}

With an argument

import { useEffect } from 'react'; 
 
const Component = () => {
    const queryString = 'http://localhost?typescript=true&hook=true';
    const  { queryParams } = useQueryParam(queryString);
 
  useEffect(() => {
      console.log(queryParams);
     // Output: { typescript: 'true', hook: 'true' }
  }, [queryParams]);
}
 

Case Two:

Importing module into file

The getQueryParams takes a string and returns an object

import { getQueryParams } from 'use-query-param';
 
OR
 
const { getQueryParams } = require('use-query-param');

Without an argument

const { queryParams } = getQueryParams(); // <== This is not a hook
 
If a URL query string exist on the browser address bar you will get an output with all the query params OR an empty object
// Output: { token: 'jdkjada9s7d9akadbjkss893asda89' }
 
OR
 
// Output: {} => Empty object

With an argument

const queryString = '?typescript=true&hook=true';
const { queryParams } = getQueryParams(queryString); // <== This is not a hook
 
// Output: { typescript: 'true', hook: 'true' }

Case Three:

Importing module into file

The setQueryParams takes an object and returns a query formatted string

import { setQueryParams } from 'use-query-param';
 
OR
 
const { setQueryParams } = require('use-query-param');

Without an argument

const { queryString } = setQueryParams(); // <== This is not a hook
 
// Output: '?token='jdkjada9s7d9akad....'

With an argument

const queryObject = { typescript: 'true', hook: 'true' };
const { queryString } = getQueryParams(queryString); // <== This is not a hook
 
// '?typescript=true&hook=true'

Note

Note that the getQueryParams and setQueryParams are not hooks, rather they are auxiliary functions

Package Sidebar

Install

npm i use-query-param

Weekly Downloads

22

Version

1.0.9

License

ISC

Unpacked Size

7.23 kB

Total Files

4

Last publish

Collaborators

  • shaolinmkz