|
@@ -10,7 +10,7 @@ const createObservable = initial => {
|
|
|
let _val = initial;
|
|
|
let _listeners = [];
|
|
|
|
|
|
- return {
|
|
|
+ const obs = {
|
|
|
_get: () => _val,
|
|
|
_set: newValue => {
|
|
|
const oldValue = _val;
|
|
@@ -25,17 +25,16 @@ const createObservable = initial => {
|
|
|
_listeners = _listeners.filter(ln => ln.callback !== callback);
|
|
|
}
|
|
|
}
|
|
|
- }
|
|
|
-}
|
|
|
+ };
|
|
|
|
|
|
-const createHook = obs => {
|
|
|
- // allow linters to pick this up as a hook
|
|
|
- const useObservable = (equality = shallowEq) => {
|
|
|
- const [val, setVal] = useState(obs._get());
|
|
|
+ // name allows linters to pick this up as a hook
|
|
|
+ const useValue = (equality = shallowEq) => {
|
|
|
+ const [val, setVal] = useState(_val);
|
|
|
useEffect(() => obs._sub(setVal, equality), [equality]);
|
|
|
return val;
|
|
|
}
|
|
|
- return useObservable;
|
|
|
+
|
|
|
+ return [obs, useValue];
|
|
|
}
|
|
|
|
|
|
const mergeState = (store, hooks, newState) => {
|
|
@@ -44,9 +43,9 @@ const mergeState = (store, hooks, newState) => {
|
|
|
if (obs) {
|
|
|
obs._set(newValue);
|
|
|
} else {
|
|
|
- const newObs = createObservable(newValue);
|
|
|
- store[key] = newObs;
|
|
|
- hooks[nameToHookName(key)] = createHook(newObs);
|
|
|
+ const [obs, hook] = createObservable(newValue);
|
|
|
+ store[key] = obs;
|
|
|
+ hooks[nameToHookName(key)] = hook;
|
|
|
}
|
|
|
});
|
|
|
}
|
|
@@ -54,8 +53,8 @@ const mergeState = (store, hooks, newState) => {
|
|
|
export const createStore = (initial, actions = {}) => {
|
|
|
const store = {};
|
|
|
const hooks = {};
|
|
|
+ mergeState(store, hooks, initial);
|
|
|
const dispatch = mapValues(actions, act => (...args) => mergeState(store, hooks, act(...args)));
|
|
|
const selector = mapValues(store, obs => obs._get);
|
|
|
- mergeState(store, hooks, initial);
|
|
|
return [hooks, dispatch, selector];
|
|
|
}
|