diff --git a/src/frontend/hooks/draftObservation.ts b/src/frontend/hooks/draftObservation.ts index 3b8af8de9..6d810e4d7 100644 --- a/src/frontend/hooks/draftObservation.ts +++ b/src/frontend/hooks/draftObservation.ts @@ -1,18 +1,34 @@ import {useStore} from 'zustand'; import {useDraftObservationContext} from '../contexts/DraftObservationContext'; -import {DraftState} from '../hooks/persistedState/usePersistedDraftObservationNew'; +import { + DraftState, + DraftStatePopulated, +} from '../hooks/persistedState/usePersistedDraftObservationNew'; +import {useCallback} from 'react'; -function defaultSelector(state: DraftState) { +function defaultSelector(state: DraftStatePopulated) { return state; } -export function useDraftObservation( - selector: (state: DraftState) => S = defaultSelector as any, +export function useDraftObservation( + selector: (state: DraftStatePopulated) => S = defaultSelector as any, ) { const {store} = useDraftObservationContext(); - const draftObservation = useStore(store, selector); - return draftObservation; + + const assertPopulatedStateSelector = useCallback( + (state: DraftState) => { + if (!state.value) { + throw new Error('No observation to read'); + } + return selector(state); + }, + [selector], + ); + + const value = useStore(store, assertPopulatedStateSelector); + + return value; } export function useDraftObservationActions() {