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

49 lines
1.3 KiB
TypeScript
Raw Normal View History

2023-03-20 10:27:22 -07:00
import { useState } from 'react';
2023-03-14 12:24:11 -07:00
import { useCreateEntity } from './useCreateEntity';
import { useDeleteEntity } from './useDeleteEntity';
import { parseEntitiesPath } from './utils';
2023-03-14 12:24:11 -07:00
import type { Entity } from '../types';
import type { EntitySchema, ExpandedEntitiesPath } from './types';
2023-03-14 12:24:11 -07:00
interface UseEntityActionsOpts<TEntity extends Entity = Entity> {
schema?: EntitySchema<TEntity>
}
interface EntityActionEndpoints {
post?: string
delete?: string
}
function useEntityActions<TEntity extends Entity = Entity, Data = any>(
expandedPath: ExpandedEntitiesPath,
2023-03-14 12:24:11 -07:00
endpoints: EntityActionEndpoints,
opts: UseEntityActionsOpts<TEntity> = {},
) {
2023-03-22 14:12:05 -07:00
const { entityType, path } = parseEntitiesPath(expandedPath);
2023-03-20 10:27:22 -07:00
const [isLoading, setIsLoading] = useState<boolean>(false);
const _delete = useDeleteEntity(entityType, { method: 'delete', url: endpoints.delete });
const create = useCreateEntity<TEntity, Data>(path, { method: 'post', url: endpoints.post }, opts);
const createEntity: typeof create = async (...args) => {
2023-03-23 13:09:00 -07:00
setIsLoading(true);
await create(...args);
setIsLoading(false);
};
2023-03-14 12:24:11 -07:00
const deleteEntity: typeof _delete = async (...args) => {
2023-03-23 13:09:00 -07:00
setIsLoading(true);
await _delete(...args);
setIsLoading(false);
};
2023-03-14 12:24:11 -07:00
return {
createEntity,
deleteEntity,
2023-03-20 10:27:22 -07:00
isLoading,
2023-03-14 12:24:11 -07:00
};
}
export { useEntityActions };