EntityStore: switch all hooks to use a callback function

This commit is contained in:
Alex Gleason
2023-03-23 19:22:26 -05:00
parent 9d12173b87
commit a530ec0202
15 changed files with 95 additions and 116 deletions

View File

@@ -1,36 +1,31 @@
import { z } from 'zod';
import { useAppDispatch } from 'soapbox/hooks';
import { useAppDispatch, useLoading } from 'soapbox/hooks';
import { importEntities } from '../actions';
import { useEntityRequest } from './useEntityRequest';
import { parseEntitiesPath, toAxiosRequest } from './utils';
import { parseEntitiesPath } from './utils';
import type { Entity } from '../types';
import type { EntityCallbacks, EntityRequest, EntitySchema, ExpandedEntitiesPath } from './types';
import type { EntityCallbacks, EntityFn, EntitySchema, ExpandedEntitiesPath } from './types';
interface UseCreateEntityOpts<TEntity extends Entity = Entity> {
schema?: EntitySchema<TEntity>
}
function useCreateEntity<TEntity extends Entity = Entity, Data = any>(
function useCreateEntity<TEntity extends Entity = Entity, Data = unknown>(
expandedPath: ExpandedEntitiesPath,
entityRequest: EntityRequest,
entityFn: EntityFn<Data>,
opts: UseCreateEntityOpts<TEntity> = {},
) {
const dispatch = useAppDispatch();
const { request, isLoading } = useEntityRequest();
const [isLoading, setPromise] = useLoading();
const { entityType, listKey } = parseEntitiesPath(expandedPath);
async function createEntity(data: Data, callbacks: EntityCallbacks<TEntity> = {}): Promise<void> {
try {
const result = await request({
...toAxiosRequest(entityRequest),
data,
});
const result = await setPromise(entityFn(data));
const schema = opts.schema || z.custom<TEntity>();
const entity = schema.parse(result.data);