MCPcopy Index your code
hub / github.com/ruucm/shadergradient / useQueryState

Function useQueryState

packages/shadergradient/src/useQueryState.ts:5–49  ·  view source on GitHub ↗
(propName: any, defaultValue: any = null)

Source from the content-addressed store, hash-verified

3import { useQueryStore } from './store'
4
5export 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
51export const useURLQueryState = () => {
52 // it's weird, but need to wrap below func as a hook

Callers 3

GradientCanvasFunction · 0.85
MeshFunction · 0.85
useControlValuesFunction · 0.85

Calls 1

updateHistoryFunction · 0.85

Tested by

no test coverage detected