Created
April 9, 2020 20:31
-
-
Save Willmo36/3dadc5b1457ab573587d3a2f4fa6327e to your computer and use it in GitHub Desktop.
fp-ts React ref proxy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function refProxy<T>( | |
ref: React.MutableRefObject<T> | |
): React.MutableRefObject<T> & { current: O.Option<T> } { | |
const p = new Proxy( | |
ref as React.MutableRefObject<T> & { current: O.Option<T> }, | |
{ | |
get: (target, prop) => { | |
if (prop === "current") { | |
return O.fromNullable(target.current); | |
} | |
return (target as any)[prop]; | |
} | |
} | |
); | |
return p; | |
} | |
function useSafeRef<T>() { | |
return refProxy(React.useRef<T | null>(null)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
how to assign to
ref.current
?