From af85c8a5671db7cdad5c6e212083e269ea48c856 Mon Sep 17 00:00:00 2001 From: Josep M Sobrepere Date: Tue, 14 Jun 2022 15:39:44 +0200 Subject: [PATCH] @react-rxjs/core: fix StrictMode error on immediate unmount --- packages/core/src/Subscribe.test.tsx | 39 +++++++++++++++++++++++++++- packages/core/src/Subscribe.tsx | 2 +- 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/packages/core/src/Subscribe.test.tsx b/packages/core/src/Subscribe.test.tsx index e383ae3..fcecc25 100644 --- a/packages/core/src/Subscribe.test.tsx +++ b/packages/core/src/Subscribe.test.tsx @@ -1,6 +1,6 @@ import { state } from "@rxstate/core" import { render, screen } from "@testing-library/react" -import React, { StrictMode, useState } from "react" +import React, { StrictMode, useState, useEffect } from "react" import { defer, EMPTY, NEVER, Observable, of, startWith } from "rxjs" import { bind, RemoveSubscribe, Subscribe as OriginalSubscribe } from "./" import { TestErrorBoundary } from "./test-helpers/TestErrorBoundary" @@ -266,6 +266,43 @@ describe("Subscribe", () => { expect(getByTestId("id").textContent).toBe("1") expect(getByTestId("value").textContent).toBe("1") }) + + it("on StrictMode: it doesn't crash if the component immediately unmounts", () => { + function App() { + const [switched, setSwitched] = useState(false) + + useEffect(() => { + setSwitched(true) + }, []) + + return ( +
+ {switched ? : } +
+ ) + } + + const ProblematicComponent = () => { + return + } + const SwitchToComponent = () => { + return
All good
+ } + + let hasError = false + + render( + { + hasError = true + }} + > + + , + ) + + expect(hasError).toBe(false) + }) }) }) diff --git a/packages/core/src/Subscribe.tsx b/packages/core/src/Subscribe.tsx index 932dff6..c14049c 100644 --- a/packages/core/src/Subscribe.tsx +++ b/packages/core/src/Subscribe.tsx @@ -77,7 +77,7 @@ export const Subscribe: React.FC<{ useEffect(() => { return () => { - subscriptionRef.current!.unsubscribe() + subscriptionRef.current?.unsubscribe() subscriptionRef.current = undefined } }, [])