Skip to content

Commit 53bb461

Browse files
authored
fix(connections): ensure that connectionInfoAccess hook value is stable (#6240)
1 parent 5c9b192 commit 53bb461

File tree

1 file changed

+19
-13
lines changed

1 file changed

+19
-13
lines changed

packages/compass-connections/src/connection-info-provider.tsx

Lines changed: 19 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import React, { createContext, useContext } from 'react';
1+
import React, { createContext, useContext, useState } from 'react';
22
import type { ConnectionInfo } from '@mongodb-js/connection-info';
33
import {
44
createServiceLocator,
@@ -88,19 +88,25 @@ export const useConnectionInfoAccess = (): ConnectionInfoAccess => {
8888
// This is stable in all environments
8989
// eslint-disable-next-line react-hooks/rules-of-hooks
9090
const connectionInfoRef = useConnectionInfoRefForId(connectionId);
91-
return {
92-
getCurrentConnectionInfo() {
93-
if (!connectionInfoRef.current) {
94-
if (process.env.NODE_ENV !== 'test') {
95-
throw new Error(
96-
'Could not find the current ConnectionInfo. Did you forget to setup the ConnectionInfoContext?'
97-
);
91+
// eslint-disable-next-line react-hooks/rules-of-hooks
92+
const [access] = useState(() => {
93+
// Return the function from useState to make sure the value doesn't change
94+
// when component re-renders
95+
return {
96+
getCurrentConnectionInfo() {
97+
if (!connectionInfoRef.current) {
98+
if (process.env.NODE_ENV !== 'test') {
99+
throw new Error(
100+
'Could not find the current ConnectionInfo. Did you forget to setup the ConnectionInfoContext?'
101+
);
102+
}
103+
return TEST_CONNECTION_INFO;
98104
}
99-
return TEST_CONNECTION_INFO;
100-
}
101-
return connectionInfoRef.current;
102-
},
103-
};
105+
return connectionInfoRef.current;
106+
},
107+
};
108+
});
109+
return access;
104110
};
105111
export const connectionInfoAccessLocator = createServiceLocator(
106112
useConnectionInfoAccess,

0 commit comments

Comments
 (0)