useDeleteEntity: support onSuccess callback
This commit is contained in:
parent
1949651b9a
commit
4783a41b78
1 changed files with 14 additions and 2 deletions
|
@ -4,16 +4,23 @@ import { deleteEntities, importEntities } from '../actions';
|
||||||
|
|
||||||
type DeleteFn<T> = (entityId: string) => Promise<T> | T;
|
type DeleteFn<T> = (entityId: string) => Promise<T> | T;
|
||||||
|
|
||||||
|
interface EntityCallbacks {
|
||||||
|
onSuccess?(): void
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Optimistically deletes an entity from the store.
|
* Optimistically deletes an entity from the store.
|
||||||
* This hook should be used to globally delete an entity from all lists.
|
* This hook should be used to globally delete an entity from all lists.
|
||||||
* To remove an entity from a single list, see `useDismissEntity`.
|
* To remove an entity from a single list, see `useDismissEntity`.
|
||||||
*/
|
*/
|
||||||
function useDeleteEntity<T = unknown>(entityType: string, deleteFn: DeleteFn<T>) {
|
function useDeleteEntity<T = unknown>(
|
||||||
|
entityType: string,
|
||||||
|
deleteFn: DeleteFn<T>,
|
||||||
|
) {
|
||||||
const dispatch = useAppDispatch();
|
const dispatch = useAppDispatch();
|
||||||
const getState = useGetState();
|
const getState = useGetState();
|
||||||
|
|
||||||
return async function deleteEntity(entityId: string): Promise<T> {
|
return async function deleteEntity(entityId: string, callbacks: EntityCallbacks = {}): Promise<T> {
|
||||||
// Get the entity before deleting, so we can reverse the action if the API request fails.
|
// Get the entity before deleting, so we can reverse the action if the API request fails.
|
||||||
const entity = getState().entities[entityType]?.store[entityId];
|
const entity = getState().entities[entityType]?.store[entityId];
|
||||||
|
|
||||||
|
@ -24,6 +31,11 @@ function useDeleteEntity<T = unknown>(entityType: string, deleteFn: DeleteFn<T>)
|
||||||
const result = await deleteFn(entityId);
|
const result = await deleteFn(entityId);
|
||||||
// Success - finish deleting entity from the state.
|
// Success - finish deleting entity from the state.
|
||||||
dispatch(deleteEntities([entityId], entityType));
|
dispatch(deleteEntities([entityId], entityType));
|
||||||
|
|
||||||
|
if (callbacks.onSuccess) {
|
||||||
|
callbacks.onSuccess();
|
||||||
|
}
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (entity) {
|
if (entity) {
|
||||||
|
|
Loading…
Reference in a new issue