Skip to content

Instantly share code, notes, and snippets.

@anderjs
Last active March 20, 2020 20:27
Show Gist options
  • Select an option

  • Save anderjs/d57fb6cb6008f9dfc655e1487be64155 to your computer and use it in GitHub Desktop.

Select an option

Save anderjs/d57fb6cb6008f9dfc655e1487be64155 to your computer and use it in GitHub Desktop.
import { useMemo } from 'react'
/**
* Generates an object of query parameters.
* @param {string} url
* @param {string []} dataset
*/
function useQuery (url) {
const queries = useMemo(() => {
const params = new URLSearchParams(url)
const data = {}
params.forEach((_, key) => {
Object.defineProperty(data, key, {
get () {
return params.get(key)
}
})
})
return data
}, [url])
return [queries]
}
/**
* @example
* const [ queries ] = useQuery('?search=samgsumg&price=33') => { search: 'samsung', price: 33 }
*/
export default useQuery
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment