import { useEffect, useState } from 'react'; import { BaseModel, CHANGE_EVENT_TYPE, EventTopic } from '../models'; import { BelongsTo } from '../models/belongs-to'; import { Id } from '../types'; import { useAsync, UseAsyncResult } from './use-async'; import { useBaseModelRelation, useSDKEventBus } from './use-models'; export type UseBelongsTo = { model: any; getByParentId: (id: Id) => UseAsyncResult; }; export const useBelongsTo = ( model: BaseModel, classProp: string, ) => { const relation = useBaseModelRelation(model, classProp); const eventBus = useSDKEventBus(); return { model: relation, getByParentId: useGetByParentId(relation, eventBus), }; }; const useGetByParentId = ( relation: BelongsTo, eventBus: EventTopic, ) => (id: Id): UseAsyncResult => { const [data, setData] = useState(); const [gotten, fetch, loading, error] = useAsync(relation.get.bind(relation)); async function handleChange() { const d = await relation.getLocal(id); setData(d); } useEffect(() => { handleChange(); }, []); useEffect(() => { eventBus.addEventListener(CHANGE_EVENT_TYPE, handleChange); return () => eventBus.removeEventListener(CHANGE_EVENT_TYPE, handleChange); }); useEffect(() => { setData(gotten); }, [gotten]); const exec = (...args: any[]) => fetch(id, ...args); return [data, exec, loading, error]; };