All files / src/store hooks.ts

41.17% Statements 35/85
33.33% Branches 16/48
13.33% Functions 2/15
38.75% Lines 31/80

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 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210                  1x 1x       28x     1x 1x                                             1x                                                           1x                                                     1x                                                         1x                                             1x         1x 27x 6x     21x 15x 15x   15x   3x     12x 16x 15x 15x 15x   15x   4x   2x           2x         1x     9x   6x       1x                    
/*
 * The coLAB project
 * Copyright (C) 2021-2023 AlbaSim, MEI, HEIG-VD, HES-SO
 *
 * Licensed under the MIT License
 */
 
import { AsyncThunk } from '@reduxjs/toolkit';
import { ColabEntity } from 'colab-rest-client';
import * as React from 'react';
import { shallowEqual, TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux';
import { AvailabilityStatus, FetchingStatus } from '../store/store';
import { AppDispatch, ColabState } from './store';
 
export { shallowEqual } from 'react-redux';
 
// Use throughout your app instead of plain `useDispatch` and `useSelector`
export const useAppDispatch = () => useDispatch<AppDispatch>();
export const useAppSelector: TypedUseSelectorHook<ColabState> = useSelector;
 
interface DataAndStatus<T> {
  status: AvailabilityStatus;
  data?: T;
}
 
function selectData<T extends ColabEntity>(
  state: ColabState,
  id: number,
  selector: (state: ColabState) => Record<number, T | FetchingStatus>,
): DataAndStatus<T> {
  const dataInStore = selector(state)[id];
 
  if (dataInStore == null) {
    return { status: 'NOT_INITIALIZED' };
  } else Iif (typeof dataInStore === 'string') {
    return { status: dataInStore };
  }
 
  return { status: 'READY', data: dataInStore };
}
 
export function useFetchById<T extends ColabEntity>(
  id: number,
  selector: (state: ColabState) => Record<number, T | FetchingStatus>,
  // eslint-disable-next-line @typescript-eslint/ban-types
  fetcher: AsyncThunk<T | null, number, {}>,
): DataAndStatus<T> {
  const dispatch = useAppDispatch();
 
  const { status, data }: DataAndStatus<T> = useAppSelector(
    state => selectData<T>(state, id, selector),
    shallowEqual,
  );
 
  React.useEffect(() => {
    Iif (status === 'NOT_INITIALIZED' && id > 0) {
      dispatch(fetcher(id));
    }
  }, [status, dispatch, fetcher, id]);
 
  Iif (status === 'NOT_INITIALIZED' && id <= 0) {
    return { status: 'ERROR' };
  }
 
  Iif (status === 'READY' && data != null) {
    return { status, data };
  }
 
  return { status };
}
 
export function useFetchList<T extends ColabEntity>(
  statusSelector: (state: ColabState) => AvailabilityStatus,
  dataSelector: (state: ColabState) => T[],
  // eslint-disable-next-line @typescript-eslint/ban-types, @typescript-eslint/no-explicit-any
  fetcher: AsyncThunk<any, void, {}>,
): { status: AvailabilityStatus; data?: T[] } {
  const dispatch = useAppDispatch();
 
  const status = useAppSelector(statusSelector);
 
  const data = useAppSelector(dataSelector, shallowEqual);
 
  React.useEffect(() => {
    Iif (status === 'NOT_INITIALIZED') {
      dispatch(fetcher());
    }
  }, [status, dispatch, fetcher]);
 
  Iif (status === 'READY' && data != null) {
    return { status, data };
  }
 
  return { status };
}
 
// TODO Ideally make only one function for useFetchList and useFetchListWithArg
 
export function useFetchListWithArg<T extends ColabEntity, U>(
  statusSelector: (state: ColabState) => AvailabilityStatus,
  dataSelector: (state: ColabState) => T[],
  // eslint-disable-next-line @typescript-eslint/ban-types, @typescript-eslint/no-explicit-any
  fetcher: AsyncThunk<any, U, {}>,
  fetcherArg: U,
): { status: AvailabilityStatus; data?: T[] } {
  const dispatch = useAppDispatch();
 
  const status = useAppSelector(statusSelector);
 
  const data = useAppSelector(dataSelector, shallowEqual);
 
  // Note : do not React.useEffect
  Iif (status === 'NOT_INITIALIZED' && fetcherArg) {
    dispatch(fetcher(fetcherArg));
  }
 
  Iif (status === 'NOT_INITIALIZED' && !fetcherArg) {
    return { status: 'ERROR' };
  }
 
  Iif (status === 'READY' && data != null) {
    return { status, data };
  }
 
  return { status };
}
 
export function useLoadDataWithArg<U>(
  statusSelector: (state: ColabState) => AvailabilityStatus,
  // eslint-disable-next-line @typescript-eslint/ban-types, @typescript-eslint/no-explicit-any
  fetcher: AsyncThunk<any, U, {}>,
  fetcherArg: U,
): AvailabilityStatus {
  const dispatch = useAppDispatch();
 
  const status = useAppSelector(statusSelector);
 
  React.useEffect(() => {
    Iif (status === 'NOT_INITIALIZED' && fetcherArg) {
      dispatch(fetcher(fetcherArg));
    }
  }, [status, dispatch, fetcher, fetcherArg]);
 
  Iif (status === 'NOT_INITIALIZED' && !fetcherArg) {
    return 'ERROR';
  }
 
  return status;
}
 
const hasOwn = Object.prototype.hasOwnProperty;
 
/**
 * kind of shallowEquals, but use shallowEqual to compare first-level-nested arrays
 */
export const customColabStateEquals = (a: unknown, b: unknown): boolean => {
  if (Object.is(a, b)) {
    return true;
  }
 
  if (typeof a === 'object' && a != null && typeof b === 'object' && b != null) {
    const aKeys = Object.keys(a).sort();
    const bKeys = Object.keys(b).sort();
 
    if (aKeys.length !== bKeys.length) {
      // keysets mismatch
      return false;
    }
 
    for (const key in a) {
      if (hasOwn.call(b, key)) {
        if (key in a) {
          const aValue = (a as { [key: string]: unknown })[key];
          const bValue = (b as { [key: string]: unknown })[key];
 
          if (!Object.is(aValue, bValue)) {
            // values mismatch
            if (Array.isArray(aValue) && Array.isArray(bValue)) {
              // but values are arrays so they may match anyway
              Iif (!shallowEqual(aValue, bValue)) {
                // nope, array does not match
                return false;
              }
            } else {
              // not arrays => no match
              return false;
            }
          }
        }
      } else {
        return false;
      }
    }
    return true;
  } else {
    return false;
  }
};
 
export const useLoadingState = () => {
  const [isLoading, setIsLoading] = React.useState<boolean>(false);
  function startLoading() {
    setIsLoading(true);
  }
  function stopLoading() {
    setIsLoading(false);
  }
  return { isLoading, startLoading, stopLoading };
};