import { useEffect , useState } from "react" ; import { Entity , EntitySchema , EntitySchemaResolver } from "../../models" ; import { useDataSource } from "./useDataSource" ; category export interface EntityFetchProps < M extends { [ Key ] : any ; } > { path ? : string ; entityId ? : string ; schema ? : EntitySchema < M > | EntitySchemaResolver < M > ; useCache ? : boolean ; } category export interface EntityFetchResult < M extends { [ Key ] : any ; } > { entity ? : Entity < M > ; dataLoading : boolean ; dataLoadingError ? : Error ; } const CACHE = { } ; param path param schema param entityId param useCache category export function useEntityFetch < M extends { [ Key ] : any ; } > ( { path , entityId , schema , useCache = false } ) { const dataSource = useDataSource ( ) ; const [ entity , setEntity ] = useState < Entity < M > | undefined > ( ) ; const [ dataLoading , setDataLoading ] = useState < boolean > ( true ) ; const [ dataLoadingError , setDataLoadingError ] = useState < Error | undefined > ( ) ; useEffect ( ( ) => { setDataLoading ( true ) ; const onEntityUpdate = ( updatedEntity ) => { CACHE [ `${ path }/${ entityId }` ] = updatedEntity ; setEntity ( updatedEntity ) ; setDataLoading ( false ) ; setDataLoadingError ( undefined ) ; } ; const onError = ( error ) => { console . error ( "ERROR fetching entity" , error ) ; setDataLoading ( false ) ; setEntity ( undefined ) ; setDataLoadingError ( error ) ; } ; if ( useCache && CACHE [ `${ path }/${ entityId }` ] ) { setEntity ( CACHE [ `${ path }/${ entityId }` ] ) ; setDataLoading ( false ) ; setDataLoadingError ( undefined ) ; return ( ) => { } ; } else if ( entityId && path && schema ) { if ( dataSource . listenEntity ) { return dataSource . listenEntity < M > ( { path , entityId , schema , onUpdate : onEntityUpdate , onError } ) ; } else { dataSource . fetchEntity < M > ( { path , entityId , schema } ) . then ( onEntityUpdate ) . catch ( onError ) ; return ( ) => { } ; } } else { onEntityUpdate ( undefined ) ; return ( ) => { } ; } } , [ entityId , path ] ) ; return { entity , dataLoading , dataLoadingError } ; }