summaryrefslogtreecommitdiffhomepage
path: root/frontend/src/@redux/hooks/async.ts
blob: 8553f427bd1792d76aacab2ffd65a098e1168fec (plain)
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
import { AsyncThunk } from "@reduxjs/toolkit";
import { useEffect } from "react";
import { log } from "../../utilites/logger";
import { useReduxAction } from "./base";

export function useAutoUpdate(item: Async.Item<any>, update: () => void) {
  useEffect(() => {
    if (item.state === "uninitialized" || item.state === "dirty") {
      update();
    }
  }, [item.state, update]);
}

export function useAutoDirtyUpdate(
  item: Async.List<any> | Async.Entity<any>,
  updateAction: AsyncThunk<any, number[], {}>
) {
  const { state, dirtyEntities } = item;
  const hasDirty = dirtyEntities.length > 0 && state === "dirty";

  const update = useReduxAction(updateAction);

  useEffect(() => {
    if (hasDirty) {
      log("info", "updating dirty entities...");
      update(dirtyEntities.map(Number));
    }
  }, [hasDirty, dirtyEntities, update]);
}