2023-03-09 13:05:27 -08:00
|
|
|
import { useEffect, useState } from 'react';
|
2023-03-13 14:23:11 -07:00
|
|
|
import z from 'zod';
|
2022-12-04 14:58:13 -08:00
|
|
|
|
|
|
|
import { useApi, useAppDispatch, useAppSelector } from 'soapbox/hooks';
|
|
|
|
|
|
|
|
import { importEntities } from '../actions';
|
|
|
|
|
|
|
|
import type { Entity } from '../types';
|
|
|
|
|
|
|
|
type EntityPath = [entityType: string, entityId: string]
|
|
|
|
|
2023-03-09 10:32:50 -08:00
|
|
|
/** Additional options for the hook. */
|
|
|
|
interface UseEntityOpts<TEntity> {
|
2023-03-13 14:23:11 -07:00
|
|
|
/** A zod schema to parse the API entity. */
|
|
|
|
schema?: z.ZodType<TEntity, z.ZodTypeDef, any>
|
2023-03-09 13:05:27 -08:00
|
|
|
/** Whether to refetch this entity every time the hook mounts, even if it's already in the store. */
|
|
|
|
refetch?: boolean
|
2023-03-09 10:32:50 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
function useEntity<TEntity extends Entity>(
|
|
|
|
path: EntityPath,
|
|
|
|
endpoint: string,
|
|
|
|
opts: UseEntityOpts<TEntity> = {},
|
|
|
|
) {
|
2022-12-04 14:58:13 -08:00
|
|
|
const api = useApi();
|
|
|
|
const dispatch = useAppDispatch();
|
|
|
|
|
|
|
|
const [entityType, entityId] = path;
|
2023-03-09 10:32:50 -08:00
|
|
|
|
2023-03-13 14:23:11 -07:00
|
|
|
const defaultSchema = z.custom<TEntity>();
|
|
|
|
const schema = opts.schema || defaultSchema;
|
2023-03-09 10:32:50 -08:00
|
|
|
|
2023-03-13 14:23:11 -07:00
|
|
|
const entity = useAppSelector(state => {
|
|
|
|
// TODO: parse after fetch, not during render.
|
|
|
|
const result = schema.safeParse(state.entities[entityType]?.store[entityId]);
|
|
|
|
return result.success ? result.data : undefined;
|
|
|
|
});
|
2022-12-04 14:58:13 -08:00
|
|
|
|
|
|
|
const [isFetching, setIsFetching] = useState(false);
|
|
|
|
const isLoading = isFetching && !entity;
|
|
|
|
|
|
|
|
const fetchEntity = () => {
|
|
|
|
setIsFetching(true);
|
|
|
|
api.get(endpoint).then(({ data }) => {
|
|
|
|
dispatch(importEntities([data], entityType));
|
|
|
|
setIsFetching(false);
|
|
|
|
}).catch(() => {
|
|
|
|
setIsFetching(false);
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
2023-03-09 13:05:27 -08:00
|
|
|
useEffect(() => {
|
|
|
|
if (!entity || opts.refetch) {
|
|
|
|
fetchEntity();
|
|
|
|
}
|
|
|
|
}, []);
|
|
|
|
|
2022-12-04 14:58:13 -08:00
|
|
|
return {
|
|
|
|
entity,
|
|
|
|
fetchEntity,
|
|
|
|
isFetching,
|
|
|
|
isLoading,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
export {
|
|
|
|
useEntity,
|
|
|
|
};
|