summaryrefslogtreecommitdiff
path: root/src/utils.js
diff options
context:
space:
mode:
Diffstat (limited to 'src/utils.js')
-rw-r--r--src/utils.js36
1 files changed, 35 insertions, 1 deletions
diff --git a/src/utils.js b/src/utils.js
index 3c072fa..c16c1b7 100644
--- a/src/utils.js
+++ b/src/utils.js
@@ -11,7 +11,7 @@ export function useWindowDimensions() {
function handleResize() { setWindowDimensions(getWindowDimensions()); }
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
- }, []);
+ });
return windowDimensions;
}
@@ -23,3 +23,37 @@ export function useDebounce(value, delay) {
}, [value, delay]);
return debouncedValue;
}
+
+export function GlobalState(initialValue) {
+ this.value = initialValue;
+ this.subscribers = [];
+ this.getValue = () => this.value;
+
+ this.setValue = (newState) => {
+ if (this.getValue() === newState) return;
+ this.value = newState;
+ this.subscribers.forEach(subscriber => subscriber(this.value));
+ }
+
+ this.subscribe = (itemToSubscribe) => {
+ if (this.subscribers.indexOf(itemToSubscribe) > -1) return
+ this.subscribers.push(itemToSubscribe);
+ }
+
+ this.unsubscribe = (itemToUnsubscribe) => {
+ this.subscribers = this.subscribers.filter(subscriber => subscriber !== itemToUnsubscribe);
+ }
+}
+
+export function useGlobalState(globalState) {
+ const [, setState] = useState();
+ const state = globalState.getValue();
+ function reRender(newState) { setState({}); }
+ useEffect(() => {
+ globalState.subscribe(reRender);
+ return () => globalState.unsubscribe(reRender);
+ })
+ function setGlobalState(newState) { globalState.setValue(newState); }
+ return [state, setGlobalState];
+}
+