Skip to content

Commit af85c8a

Browse files
committed
@react-rxjs/core: fix StrictMode error on immediate unmount
1 parent 26b6460 commit af85c8a

File tree

2 files changed

+39
-2
lines changed

2 files changed

+39
-2
lines changed

packages/core/src/Subscribe.test.tsx

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { state } from "@rxstate/core"
22
import { render, screen } from "@testing-library/react"
3-
import React, { StrictMode, useState } from "react"
3+
import React, { StrictMode, useState, useEffect } from "react"
44
import { defer, EMPTY, NEVER, Observable, of, startWith } from "rxjs"
55
import { bind, RemoveSubscribe, Subscribe as OriginalSubscribe } from "./"
66
import { TestErrorBoundary } from "./test-helpers/TestErrorBoundary"
@@ -266,6 +266,43 @@ describe("Subscribe", () => {
266266
expect(getByTestId("id").textContent).toBe("1")
267267
expect(getByTestId("value").textContent).toBe("1")
268268
})
269+
270+
it("on StrictMode: it doesn't crash if the component immediately unmounts", () => {
271+
function App() {
272+
const [switched, setSwitched] = useState(false)
273+
274+
useEffect(() => {
275+
setSwitched(true)
276+
}, [])
277+
278+
return (
279+
<div className="App">
280+
{switched ? <SwitchToComponent /> : <ProblematicComponent />}
281+
</div>
282+
)
283+
}
284+
285+
const ProblematicComponent = () => {
286+
return <Subscribe></Subscribe>
287+
}
288+
const SwitchToComponent = () => {
289+
return <div>All good</div>
290+
}
291+
292+
let hasError = false
293+
294+
render(
295+
<TestErrorBoundary
296+
onError={() => {
297+
hasError = true
298+
}}
299+
>
300+
<App />
301+
</TestErrorBoundary>,
302+
)
303+
304+
expect(hasError).toBe(false)
305+
})
269306
})
270307
})
271308

packages/core/src/Subscribe.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ export const Subscribe: React.FC<{
7777

7878
useEffect(() => {
7979
return () => {
80-
subscriptionRef.current!.unsubscribe()
80+
subscriptionRef.current?.unsubscribe()
8181
subscriptionRef.current = undefined
8282
}
8383
}, [])

0 commit comments

Comments
 (0)