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

37 wiersze
1.0 KiB
TypeScript
Czysty Zwykły widok Historia

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