Skip to content

Commit

Permalink
feat(debounce): add debounce feature for set query
Browse files Browse the repository at this point in the history
  • Loading branch information
chornos13 committed Jan 31, 2021
1 parent 71ad255 commit 82ff2bb
Showing 1 changed file with 16 additions and 8 deletions.
24 changes: 16 additions & 8 deletions src/helpers/QueryUrl/useUrlQuery.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import QueryUrl, { QueryUrlOptions } from 'helpers/QueryUrl/QueryUrl'
import { useMemo, useRef, useState } from 'react'
import queryString from 'query-string'
import _ from 'lodash'

export type UseUrlQueryOptions = {} & QueryUrlOptions

const DEBOUNCE_WAIT = 500

type QueryUrlReadOnly<T> = Omit<T, 'set' | 'remove'>
function useUrlQuery(_options?: UseUrlQueryOptions) {
const { ...queryUrlOptions } = { ..._options }
Expand All @@ -28,6 +31,15 @@ function useUrlQuery(_options?: UseUrlQueryOptions) {
}, [count])

const extraSetter = useMemo(() => {
async function setQuery(fn: (helper: QueryUrl) => void | Promise<void>) {
await fn(queryUrl)
setCount((prevState) => prevState + 1)
}

function setQuerySync(fn: (helper: QueryUrl) => void) {
fn(queryUrl)
setCount((prevState) => prevState + 1)
}
return {
transformUrl(keys: string) {
return getStringQuery(keys)
Expand All @@ -38,14 +50,10 @@ function useUrlQuery(_options?: UseUrlQueryOptions) {
}
return [keys, getStringQuery()]
},
async setQuery(fn: (helper: QueryUrl) => void | Promise<void>) {
await fn(queryUrl)
setCount((prevState) => prevState + 1)
},
setQuerySync(fn: (helper: QueryUrl) => void) {
fn(queryUrl)
setCount((prevState) => prevState + 1)
},
setQuery,
setQuerySync,
setQueryDebounce: _.debounce(setQuery, DEBOUNCE_WAIT),
setQuerySyncDebounce: _.debounce(setQuerySync, DEBOUNCE_WAIT),
query: queryUrl.query as QueryUrlReadOnly<typeof queryUrl.query>,
sorted: queryUrl.sorted as QueryUrlReadOnly<typeof queryUrl.sorted>,
filtered: queryUrl.filtered as QueryUrlReadOnly<typeof queryUrl.filtered>,
Expand Down

0 comments on commit 82ff2bb

Please sign in to comment.