All files / src/store index.ts

36.36% Statements 8/22
14.29% Branches 1/7
16.67% Functions 1/6
38.1% Lines 8/21

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39    2x 2x 2x   2x                                                   2x 2x 2x   2x    
import { useState, useEffect, useCallback } from 'react';
 
let globalState: any = {};
let listeners: any[] = [];
let actions: any = {};
 
export const useStore = (shouldListen = true) => {
  const setState = useState(globalState)[1];
 
  const dispatch = useCallback((actionIdentifier: string, payload: any) => {
    const newState = actions[actionIdentifier](globalState, payload);
    globalState = { ...globalState, ...newState };
    for (const listener of listeners) {
      listener(globalState);
    }
  }, []);
 
  useEffect(() => {
    if (shouldListen) {
      listeners.push(setState);
    }
 
    return () => {
      if (shouldListen) {
        listeners = listeners.filter(li => li !== setState);
      }
    };
  }, [setState, shouldListen]);
 
  return [globalState, dispatch];
};
 
export const initStore = (userActions: any, initialState: any) => {
  Eif (initialState) {
    globalState = { ...globalState, ...initialState };
  }
  actions = { ...actions, ...userActions };
};