|
|
import { useCallback, useReducer, useRef } from 'react' |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
export function useGenericSelector<T>( |
|
|
selector: () => T, |
|
|
equalityFn: (a: T | null, b: T) => boolean |
|
|
): [state: T, update: () => void] { |
|
|
const [, forceRender] = useReducer(s => s + 1, 0) |
|
|
|
|
|
const latestSubscriptionCallbackError = useRef<Error | undefined>() |
|
|
const latestSelector = useRef<() => T>(() => null as any) |
|
|
const latestSelectedState = useRef<T | null>(null) |
|
|
let selectedState: T |
|
|
|
|
|
try { |
|
|
if ( |
|
|
selector !== latestSelector.current || |
|
|
latestSubscriptionCallbackError.current |
|
|
) { |
|
|
const selectorResult = selector() |
|
|
|
|
|
if (equalityFn(latestSelectedState.current, selectorResult)) { |
|
|
selectedState = latestSelectedState.current as T |
|
|
} else { |
|
|
selectedState = selectorResult |
|
|
} |
|
|
} else { |
|
|
selectedState = latestSelectedState.current as T |
|
|
} |
|
|
} catch (err) { |
|
|
if (latestSubscriptionCallbackError.current && isError(err)) { |
|
|
err.message += `\nThe error may be correlated with this previous error:\n${latestSubscriptionCallbackError.current.stack}\n\n` |
|
|
} |
|
|
|
|
|
throw err |
|
|
} |
|
|
|
|
|
latestSelector.current = selector |
|
|
latestSelectedState.current = selectedState |
|
|
latestSubscriptionCallbackError.current = undefined |
|
|
|
|
|
const update = useCallback(() => { |
|
|
try { |
|
|
const newSelectedState = latestSelector.current() |
|
|
|
|
|
if (equalityFn(latestSelectedState.current, newSelectedState)) { |
|
|
return |
|
|
} |
|
|
|
|
|
latestSelectedState.current = newSelectedState |
|
|
} catch (err) { |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if (err instanceof Error) { |
|
|
latestSubscriptionCallbackError.current = err |
|
|
} else { |
|
|
latestSubscriptionCallbackError.current = new Error(String(err)) |
|
|
} |
|
|
} |
|
|
|
|
|
forceRender() |
|
|
|
|
|
|
|
|
|
|
|
}, []) |
|
|
|
|
|
return [selectedState, update] |
|
|
} |
|
|
|
|
|
function isError(error: any): error is Error { |
|
|
return error instanceof Error |
|
|
} |
|
|
|