Skip to content

Commit

Permalink
fix: optimize useObserve
Browse files Browse the repository at this point in the history
  • Loading branch information
mbret committed Apr 27, 2024
1 parent 62ef96b commit 1f301b3
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 5 deletions.
40 changes: 38 additions & 2 deletions src/lib/binding/useObserve.test.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { afterEach, describe, expect, it } from "vitest"
import { BehaviorSubject, Subject, map, of, timer } from "rxjs"
import { useObserve } from "./useObserve"
import { act, render, renderHook, cleanup } from "@testing-library/react"
import React, { memo, useEffect, useRef } from "react"
import { render, renderHook, cleanup } from "@testing-library/react"
import React, { act, memo, useEffect, useRef } from "react"
import { useBehaviorSubject } from "./useBehaviorSubject"
import { waitForTimeout } from "../../tests/utils"

afterEach(() => {
cleanup()
Expand Down Expand Up @@ -180,4 +181,39 @@ describe("useObserve", () => {

expect(await findByText("10")).toBeDefined()
})

it(`does not re-render when observer complete`, async () => {
const subject = new Subject<number>()
let numberOfRenders = 0

const MyComponent = () => {
useObserve(subject)

numberOfRenders++

return null
}

render(<MyComponent />)

expect(numberOfRenders).toBe(1)

await waitForTimeout(10)

act(() => {

Check failure on line 203 in src/lib/binding/useObserve.test.tsx

View workflow job for this annotation

GitHub Actions / Release

src/lib/binding/useObserve.test.tsx > useObserve > does not re-render when observer complete

TypeError: act is not a function ❯ src/lib/binding/useObserve.test.tsx:203:5
subject.next(10)
})

expect(numberOfRenders).toBe(2)

await waitForTimeout(10)

act(() => {
subject.complete()
})

await waitForTimeout(10)

expect(numberOfRenders).toBe(2)
})
})
4 changes: 1 addition & 3 deletions src/lib/binding/useObserve.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@ import {
distinctUntilChanged,
catchError,
EMPTY,
finalize,
type BehaviorSubject
type BehaviorSubject,
} from "rxjs"
import { useLiveRef } from "../utils/useLiveRef"
import { primitiveEqual } from "../utils/primitiveEqual"
Expand Down Expand Up @@ -88,7 +87,6 @@ export function useObserve<T>(
tap((value) => {
valueRef.current = value as any
}),
finalize(next),
catchError((error) => {
console.error(error)

Expand Down

0 comments on commit 1f301b3

Please sign in to comment.