From e284bdc869a89af631500a3e4175a9c9f4f55940 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rub=C3=A9n=20Norte?= Date: Wed, 4 Oct 2023 09:50:43 -0700 Subject: [PATCH] Check if devtools hook on/off methods are defined before using them in AppContainer (#39808) Summary: Pull Request resolved: https://github.com/facebook/react-native/pull/39808 I've been doing some tests where I disable React DevTools locally and this code has been crashing because React Fast Refresh defines the React DevTools hook if DevTools didn't ([pointer](https://github.com/facebook/react/blob/85c2b519b54269811002d26f4f711809ef68f123/packages/react-refresh/src/ReactFreshRuntime.js#L453-L475)), and it doesn't actually define the `on` and `off` methods, which makes this throw. This changes `AppContainer` to check if the methods are defined before using them. Changelog: [internal] Reviewed By: hoxyq Differential Revision: D49909258 fbshipit-source-id: 3b0c1f37601a1cbe38f80ca3a20ffe2348a21aaf --- .../Libraries/ReactNative/AppContainer.js | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/packages/react-native/Libraries/ReactNative/AppContainer.js b/packages/react-native/Libraries/ReactNative/AppContainer.js index a17b3642398..1756383c926 100644 --- a/packages/react-native/Libraries/ReactNative/AppContainer.js +++ b/packages/react-native/Libraries/ReactNative/AppContainer.js @@ -94,10 +94,12 @@ class AppContainer extends React.Component { this._reactDevToolsAgentListener = () => this.mountReactDevToolsOverlays(); - reactDevToolsHook.on( - 'react-devtools', - this._reactDevToolsAgentListener, - ); + if (reactDevToolsHook.on != null) { + reactDevToolsHook.on( + 'react-devtools', + this._reactDevToolsAgentListener, + ); + } } } } @@ -108,7 +110,10 @@ class AppContainer extends React.Component { this._subscription.remove(); } - if (reactDevToolsHook != null && this._reactDevToolsAgentListener != null) { + if ( + reactDevToolsHook?.off != null && + this._reactDevToolsAgentListener != null + ) { reactDevToolsHook.off('react-devtools', this._reactDevToolsAgentListener); } }