|
1 |
| -import React, { createContext, useContext } from 'react'; |
| 1 | +import React, { createContext, useContext, useState } from 'react'; |
2 | 2 | import type { ConnectionInfo } from '@mongodb-js/connection-info';
|
3 | 3 | import {
|
4 | 4 | createServiceLocator,
|
@@ -88,19 +88,25 @@ export const useConnectionInfoAccess = (): ConnectionInfoAccess => {
|
88 | 88 | // This is stable in all environments
|
89 | 89 | // eslint-disable-next-line react-hooks/rules-of-hooks
|
90 | 90 | 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; |
98 | 104 | }
|
99 |
| - return TEST_CONNECTION_INFO; |
100 |
| - } |
101 |
| - return connectionInfoRef.current; |
102 |
| - }, |
103 |
| - }; |
| 105 | + return connectionInfoRef.current; |
| 106 | + }, |
| 107 | + }; |
| 108 | + }); |
| 109 | + return access; |
104 | 110 | };
|
105 | 111 | export const connectionInfoAccessLocator = createServiceLocator(
|
106 | 112 | useConnectionInfoAccess,
|
|
0 commit comments