Skip to content

Instantly share code, notes, and snippets.

@lemonmade
Created November 30, 2017 14:54
Show Gist options
  • Save lemonmade/d48923fc8a684427a4283986f2ecde9e to your computer and use it in GitHub Desktop.
Save lemonmade/d48923fc8a684427a4283986f2ecde9e to your computer and use it in GitHub Desktop.
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