Add useDismissEntity hook, update useDeleteEntity to match
This commit is contained in:
parent
3d72e6305f
commit
b76559f24a
2 changed files with 31 additions and 6 deletions
|
@ -2,17 +2,18 @@ import { useAppDispatch, useGetState } from 'soapbox/hooks';
|
|||
|
||||
import { deleteEntities, importEntities } from '../actions';
|
||||
|
||||
interface DeleteEntityResult<T> {
|
||||
result: T
|
||||
}
|
||||
|
||||
type DeleteFn<T> = (entityId: string) => Promise<T> | T;
|
||||
|
||||
/**
|
||||
* Optimistically deletes an entity from the store.
|
||||
* This hook should be used to globally delete an entity from all lists.
|
||||
* To remove an entity from a single list, see `useDismissEntity`.
|
||||
*/
|
||||
function useDeleteEntity<T = unknown>(entityType: string, deleteFn: DeleteFn<T>) {
|
||||
const dispatch = useAppDispatch();
|
||||
const getState = useGetState();
|
||||
|
||||
return async function deleteEntity(entityId: string): Promise<DeleteEntityResult<T>> {
|
||||
return async function deleteEntity(entityId: string): Promise<T> {
|
||||
// Get the entity before deleting, so we can reverse the action if the API request fails.
|
||||
const entity = getState().entities[entityType]?.store[entityId];
|
||||
|
||||
|
@ -23,7 +24,7 @@ function useDeleteEntity<T = unknown>(entityType: string, deleteFn: DeleteFn<T>)
|
|||
const result = await deleteFn(entityId);
|
||||
// Success - finish deleting entity from the state.
|
||||
dispatch(deleteEntities([entityId], entityType));
|
||||
return { result };
|
||||
return result;
|
||||
} catch (e) {
|
||||
if (entity) {
|
||||
// If the API failed, reimport the entity.
|
||||
|
|
24
app/soapbox/entity-store/hooks/useDismissEntity.ts
Normal file
24
app/soapbox/entity-store/hooks/useDismissEntity.ts
Normal file
|
@ -0,0 +1,24 @@
|
|||
import { useAppDispatch } from 'soapbox/hooks';
|
||||
|
||||
import { dismissEntities } from '../actions';
|
||||
|
||||
type EntityPath = [entityType: string, listKey: string]
|
||||
type DismissFn<T> = (entityId: string) => Promise<T> | T;
|
||||
|
||||
/**
|
||||
* Removes an entity from a specific list.
|
||||
* To remove an entity globally from all lists, see `useDeleteEntity`.
|
||||
*/
|
||||
function useDismissEntity<T = unknown>(path: EntityPath, dismissFn: DismissFn<T>) {
|
||||
const [entityType, listKey] = path;
|
||||
const dispatch = useAppDispatch();
|
||||
|
||||
// TODO: optimistic dismissing
|
||||
return async function dismissEntity(entityId: string): Promise<T> {
|
||||
const result = await dismissFn(entityId);
|
||||
dispatch(dismissEntities([entityId], entityType, listKey));
|
||||
return result;
|
||||
};
|
||||
}
|
||||
|
||||
export { useDismissEntity };
|
Loading…
Reference in a new issue