Skip to content

Commit

Permalink
Prevent unwanted dispose in development when Strict Mode is enabled (#68
Browse files Browse the repository at this point in the history
)

* Prevent unwanted dispose in development when Strict Mode is enabled (#67)

* Suggestion on making the ConfigCatClient reference tracking a bit more robust

* Bump version
  • Loading branch information
adams85 authored Feb 4, 2025
1 parent 133e03b commit 9577f33
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 17 deletions.
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "configcat-react",
"version": "4.8.0",
"version": "4.8.1",
"scripts": {
"build": "npm run build:esm && npm run build:cjs",
"build:esm": "tsc -p tsconfig.build.esm.json && gulp esm",
Expand Down
25 changes: 11 additions & 14 deletions src/ConfigCatProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,26 +18,28 @@ type ConfigCatProviderProps = {

type ConfigCatProviderState = ConfigCatContextData;

const initializedClients = new Map<string, number>();
type AugmentedConfigCatClient = IConfigCatClient & {
$reactSdk_providers?: Set<ConfigCatProvider>;
}

class ConfigCatProvider extends Component<PropsWithChildren<ConfigCatProviderProps>, ConfigCatProviderState, {}> {
private configChangedHandler?: (newConfig: IConfig) => void;

constructor(props: ConfigCatProviderProps) {
super(props);

const client: IConfigCatClient = !isServerContext()
const client = (!isServerContext()
? this.initializeConfigCatClient()
: new ConfigCatClientStub();
: new ConfigCatClientStub()
) as AugmentedConfigCatClient;

const providers = client.$reactSdk_providers ??= new Set();
providers.add(this);

this.state = { client };
}

componentDidMount(): void {
const { sdkKey } = this.props;

initializedClients.set(sdkKey, (initializedClients.get(sdkKey) ?? 0) + 1);

this.configChangedHandler = newConfig => this.reactConfigChanged(newConfig);

this.state.client.waitForReady().then(() => {
Expand All @@ -56,14 +58,9 @@ class ConfigCatProvider extends Component<PropsWithChildren<ConfigCatProviderPro
delete this.configChangedHandler;
}

const { sdkKey } = this.props;

const refCount = (initializedClients.get(sdkKey) ?? 1) - 1;
initializedClients.set(sdkKey, refCount);

if (refCount <= 0) {
const providers = (this.state.client as AugmentedConfigCatClient).$reactSdk_providers;
if (providers?.delete(this) && !providers.size) {
this.state.client.dispose();
initializedClients.delete(sdkKey);
}
}

Expand Down

0 comments on commit 9577f33

Please sign in to comment.