Created
May 18, 2020 14:55
-
-
Save TianyiLi/fb275688e9ff31bb463068e84619b77e to your computer and use it in GitHub Desktop.
useSet
This file contains 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
import { useState, Dispatch, SetStateAction, useMemo } from 'react'; | |
const reactiveKeys = ['add', 'clear', 'delete']; | |
const reactive = <K>(set: Set<K>, setSet: Dispatch<SetStateAction<Set<K>>>) => { | |
const _proxy = Proxy.revocable(set, { | |
get(target, value: keyof Set<K>) { | |
if (reactiveKeys.includes(value)) { | |
return (arg: K) => { | |
target[value as 'add' | 'clear' | 'delete'].bind(target)(arg); | |
setSet(new Set([...target])); | |
_proxy.revoke(); | |
}; | |
} else { | |
return typeof target[value] === 'function' | |
? (target[value] as Function).bind(target) | |
: target[value]; | |
} | |
}, | |
}); | |
return _proxy.proxy; | |
}; | |
export const useSet = <K>(initial?: Iterable<K>) => { | |
const [set, setSet] = useState(new Set(initial)); | |
return useMemo(() => reactive(set, setSet), [set]); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment