Преглед изворни кода

Final clean up, there, the good parts of redux in 60 lines

Kirk Trombley пре 5 година
родитељ
комит
2665da5114
1 измењених фајлова са 11 додато и 12 уклоњено
  1. 11 12
      client/src/store.js

+ 11 - 12
client/src/store.js

@@ -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];
 }