(propName: any, defaultValue: any = null)
| 3 | import { useQueryStore } from './store' |
| 4 | |
| 5 | export const useQueryState = (propName: any, defaultValue: any = null) => { |
| 6 | const selector = useCallback( |
| 7 | (state) => |
| 8 | typeof state[propName] !== 'undefined' ? state[propName] : defaultValue, |
| 9 | [propName, defaultValue] |
| 10 | ) |
| 11 | const globalValue = useQueryStore(selector) |
| 12 | const _setGlobalValue = useCallback( |
| 13 | (valueFun) => |
| 14 | useQueryStore.setState({ |
| 15 | [propName]: valueFun(useQueryStore.getState()[propName]), |
| 16 | }), |
| 17 | [propName] |
| 18 | ) |
| 19 | |
| 20 | const setQueryValue = useCallback( |
| 21 | (newVal) => { |
| 22 | _setGlobalValue((currentState: any) => { |
| 23 | if (typeof newVal === 'function') { |
| 24 | newVal = newVal(currentState || defaultValue) |
| 25 | } |
| 26 | if (Number.isFinite(newVal)) { |
| 27 | newVal = parseFloat(newVal.toFixed(2)) |
| 28 | } |
| 29 | |
| 30 | // defer update of URL |
| 31 | setTimeout(() => { |
| 32 | const query = useQueryStore.getState() |
| 33 | updateHistory( |
| 34 | qs.stringifyUrl( |
| 35 | // @ts-ignore |
| 36 | { url: window.location.pathname, query }, |
| 37 | { skipNull: true, arrayFormat: 'index' } |
| 38 | ) |
| 39 | ) |
| 40 | }, 0) |
| 41 | |
| 42 | return newVal |
| 43 | }) |
| 44 | }, |
| 45 | [_setGlobalValue] |
| 46 | ) |
| 47 | |
| 48 | return [globalValue, setQueryValue] |
| 49 | } |
| 50 | |
| 51 | export const useURLQueryState = () => { |
| 52 | // it's weird, but need to wrap below func as a hook |
no test coverage detected