Created
November 30, 2017 14:54
-
-
Save lemonmade/d48923fc8a684427a4283986f2ecde9e to your computer and use it in GitHub Desktop.
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 {Component} from 'react'; | |
const cache = new WeakMap<Component<any, any>, Map<string, any>>(); | |
export function toggleState<S>(component: Component<any, S>, key: keyof S) { | |
const cachedToggles = cache.get(component) || new Map(); | |
if (cachedToggles.has(key)) { return cachedToggles.get(key); } | |
const toggle = () => component.setState((state) => ({[key]: !state[key]})); | |
cachedToggles.set(key, toggle); | |
cache.set(component, cachedToggles); | |
return toggle; | |
} | |
// Example usage: | |
// return <Popover onClose={toggleState(this, 'popoverVisible')} /> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment