import { useEffect, useState } from "react"; import { Entity, EntityCollection, FireCMSContext, User } from "../../types"; import { useDataSource } from "./useDataSource"; import { useNavigationController } from "../useNavigationController"; import { useFireCMSContext } from "../useFireCMSContext"; /** * @group Hooks and utilities */ export interface EntityFetchProps, UserType extends User = User> { path: string; entityId?: string; collection: EntityCollection; useCache?: boolean; } /** * @group Hooks and utilities */ export interface EntityFetchResult> { entity?: Entity, dataLoading: boolean, dataLoadingError?: Error } const CACHE: Record | undefined> = {}; /** * This hook is used to fetch an entity. * It gives real time updates if the datasource supports it. * @param path * @param collection * @param entityId * @param useCache * @group Hooks and utilities */ export function useEntityFetch, UserType extends User>( { path: inputPath, entityId, collection, useCache = false }: EntityFetchProps): EntityFetchResult { const dataSource = useDataSource(collection); const navigationController = useNavigationController(); const path = navigationController.resolveAliasesFrom(inputPath); const context: FireCMSContext = useFireCMSContext(); const [entity, setEntity] = useState | undefined>(); const [dataLoading, setDataLoading] = useState(true); const [dataLoadingError, setDataLoadingError] = useState(); useEffect(() => { setDataLoading(true); const onEntityUpdate = async (updatedEntity: Entity | undefined) => { if (collection.callbacks?.onFetch && updatedEntity) { try { updatedEntity = await collection.callbacks.onFetch({ collection, path, entity: updatedEntity, context }); } catch (e: any) { console.error(e); } } CACHE[`${path}/${entityId}`] = updatedEntity; setEntity(updatedEntity); setDataLoading(false); setDataLoadingError(undefined); }; const onError = (error: Error) => { console.error("ERROR fetching entity", error); setDataLoading(false); setEntity(undefined); setDataLoadingError(error); }; if (entityId && useCache && CACHE[`${path}/${entityId}`]) { setEntity(CACHE[`${path}/${entityId}`]); setDataLoading(false); setDataLoadingError(undefined); // eslint-disable-next-line @typescript-eslint/no-empty-function return () => { }; } else if (entityId && path && collection) { if (dataSource.listenEntity) { return dataSource.listenEntity({ path, entityId, collection, onUpdate: onEntityUpdate, onError }); } else { dataSource.fetchEntity({ path, entityId, collection }) .then(onEntityUpdate) .catch(onError); return () => { }; } } // if no entityId is provided we do nothing else { onEntityUpdate(undefined); return () => { }; } }, [entityId, path]); return { entity, dataLoading, dataLoadingError }; }