Skip to content

Commit

Permalink
fix(observable-hooks): check sync emissions on useObservableEgarState
Browse files Browse the repository at this point in the history
fix #86
  • Loading branch information
crimx committed Nov 10, 2021
1 parent 60fc8e1 commit 7df8b71
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -65,4 +65,22 @@ describe('useObservableEagerState', () => {
expect(result.error).toBeInstanceOf(Error)
expect(result.error.message).toBe('oops')
})

it('should not ignore sync emission between the two subscriptions', () => {
const spy = jest.fn()
const outer$ = new BehaviorSubject(1)
let isInvokedSideEffect = false
const { result } = renderHook(() => {
const state = useObservableEagerState(outer$)
if (!isInvokedSideEffect) {
isInvokedSideEffect = true
outer$.next(2)
}
spy(state)
return state
})
expect(result.current).toBe(2)
expect(spy).toHaveBeenCalledTimes(2)
expect(spy).toHaveBeenCalledWith(2)
})
})
11 changes: 11 additions & 0 deletions packages/observable-hooks/src/use-observable-eager-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@ export function useObservableEagerState<TState>(
// keep in closure for checking staleness
const input$ = state$Ref.current

let secondInitialValue = state

const subscription = input$.subscribe({
next: value => {
if (input$ !== state$Ref.current) {
Expand All @@ -66,6 +68,8 @@ export function useObservableEagerState<TState>(
// ignore synchronous value
// prevent initial re-rendering
setState(value)
} else {
secondInitialValue = value
}
},
error: error => {
Expand All @@ -78,6 +82,13 @@ export function useObservableEagerState<TState>(
}
})

if (!isAsyncEmissionRef.current) {
// fix #86 where sync emission may happen before useEffect
if (secondInitialValue !== state) {
setState(secondInitialValue)
}
}

isAsyncEmissionRef.current = true

return () => {
Expand Down

0 comments on commit 7df8b71

Please sign in to comment.