bigbuffet-rw/packages/pl-fe/src/entity-store/hooks/useIncrementEntity.ts
marcin mikołajczak 966b04fdf0 Call it pl-fe internally
Signed-off-by: marcin mikołajczak <git@mkljczk.pl>
2024-08-28 13:41:08 +02:00

38 lines
1.1 KiB
TypeScript

import { useAppDispatch } from 'pl-fe/hooks/useAppDispatch';
import { useLoading } from 'pl-fe/hooks/useLoading';
import { incrementEntities } from '../actions';
import { parseEntitiesPath } from './utils';
import type { EntityFn, ExpandedEntitiesPath } from './types';
/**
* Increases (or decreases) the `totalCount` in the entity list by the specified amount.
* This only works if the API returns an `X-Total-Count` header and your components read it.
*/
const useIncrementEntity = (
expandedPath: ExpandedEntitiesPath,
diff: number,
entityFn: EntityFn<string>,
) => {
const dispatch = useAppDispatch();
const [isLoading, setPromise] = useLoading();
const { entityType, listKey } = parseEntitiesPath(expandedPath);
const incrementEntity = async (entityId: string): Promise<void> => {
dispatch(incrementEntities(entityType, listKey, diff));
try {
await setPromise(entityFn(entityId));
} catch (e) {
dispatch(incrementEntities(entityType, listKey, diff * -1));
}
};
return {
incrementEntity,
isLoading,
};
};
export { useIncrementEntity };