bigbuffet-rw/app/soapbox/entity-store/hooks/useIncrementEntity.ts

37 lines
1 KiB
TypeScript
Raw Normal View History

import { useAppDispatch, useLoading } from 'soapbox/hooks';
2023-03-22 17:45:02 -07:00
import { incrementEntities } from '../actions';
import { parseEntitiesPath } from './utils';
import type { EntityFn, ExpandedEntitiesPath } from './types';
2023-03-22 17:45:02 -07:00
/**
* 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.
*/
function useIncrementEntity(
2023-03-22 17:45:02 -07:00
expandedPath: ExpandedEntitiesPath,
diff: number,
entityFn: EntityFn<string>,
2023-03-22 17:45:02 -07:00
) {
const dispatch = useAppDispatch();
const [isLoading, setPromise] = useLoading();
const { entityType, listKey } = parseEntitiesPath(expandedPath);
2023-03-22 17:45:02 -07:00
async function incrementEntity(entityId: string): Promise<void> {
dispatch(incrementEntities(entityType, listKey, diff));
2023-03-22 17:45:02 -07:00
try {
await setPromise(entityFn(entityId));
2023-03-22 17:45:02 -07:00
} catch (e) {
dispatch(incrementEntities(entityType, listKey, diff * -1));
}
}
return {
incrementEntity,
isLoading,
2023-03-22 17:45:02 -07:00
};
}
export { useIncrementEntity };