Add useDismissEntity hook, update useDeleteEntity to match

develop^2
Alex Gleason 2023-03-22 14:40:18 -05:00
rodzic 3d72e6305f
commit b76559f24a
Nie znaleziono w bazie danych klucza dla tego podpisu
ID klucza GPG: 7211D1F99744FBB7
2 zmienionych plików z 31 dodań i 6 usunięć

Wyświetl plik

@ -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.

Wyświetl plik

@ -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 };