All files / src/utils/hooks useFilter.ts

76.92% Statements 10/13
75% Branches 3/4
66.66% Functions 4/6
76.92% Lines 10/13

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 40 41 42 43 44 45                  66x         66x       12x   12x                 66x 30x 30x 12x   12x               30x    
import { DynamicFilterResponseProps } from "@props/RecordProps";
import { getDynamicFilters } from "@utils/FetchUtils";
import { useEffect, useReducer } from "react";
 
export type FiltersStateType = {
  dynamicFilters: Array<DynamicFilterResponseProps>;
  defaultFilter?: DynamicFilterResponseProps;
};
 
export const filtersInitialState: FiltersStateType = {
  dynamicFilters: [],
  defaultFilter: undefined,
};
 
export const filtersReducer = (state: unknown, action: {
  type: 'set';
  payload: FiltersStateType;
}): FiltersStateType => {
  switch (action.type) {
    case 'set':
      return {
        dynamicFilters: action.payload.dynamicFilters,
        defaultFilter: action.payload.defaultFilter
      };
    default:
      throw new Error("Not support action ", action.type);
  }
};
 
export const useFilter = (domainName: string, displayDefault?: boolean, refresh?: number): [Array<DynamicFilterResponseProps>, DynamicFilterResponseProps | undefined] => {
  const [state, dispatch] = useReducer(filtersReducer, filtersInitialState);
  useEffect(() => {
    getDynamicFilters(domainName, (displayDefault ?? true))
      .then((filters: Array<DynamicFilterResponseProps>) => {
        dispatch({
          type: 'set', payload: {
            dynamicFilters: filters,
            defaultFilter: filters?.find(f => f.isDefault === true)
          }
        });
      }).catch(e => console.error(`Failed to get filter of domain ${domainName}: ${e}`));
  }, [domainName, displayDefault, refresh]);
  return [state.dynamicFilters, state.defaultFilter];
};