Skip to content

Commit

Permalink
fix(clerk-react): Properly fire onLoad event when clerk-js is already…
Browse files Browse the repository at this point in the history
… loaded (#2757) (#2767)

In case of mounting-unmounting-mounting the `IsomorphicClerk.addOnLoaded` would not fire correctly, hence `derivedState` would return the initialState instead of the client side state.

In addition to the above fix, we are now cleaning up the IsomorphicClerk instance when the provider is unmounted.

(cherry picked from commit 6ac9e71)

Co-authored-by: panteliselef <[email protected]>
  • Loading branch information
clerk-cookie and panteliselef authored Feb 9, 2024
1 parent ce7b4d1 commit 4a05f2e
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/brown-lemons-film.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@clerk/clerk-react': patch
---

Properly fire onLoad event when clerk-js is already loaded.
6 changes: 6 additions & 0 deletions packages/react/src/contexts/ClerkContextProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -107,5 +107,11 @@ const useLoadedIsomorphicClerk = (options: IsomorphicClerkOptions) => {
isomorphicClerk.addOnLoaded(() => setLoaded(true));
}, []);

React.useEffect(() => {
return () => {
IsomorphicClerk.clearInstance();
};
}, []);

return { isomorphicClerk, loaded };
};
12 changes: 11 additions & 1 deletion packages/react/src/isomorphicClerk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ export default class IsomorphicClerk implements IsomorphicLoadedClerk {
return this.#loaded;
}

static #instance: IsomorphicClerk;
static #instance: IsomorphicClerk | null | undefined;

static getOrCreateInstance(options: IsomorphicClerkOptions) {
// During SSR: a new instance should be created for every request
Expand All @@ -187,6 +187,10 @@ export default class IsomorphicClerk implements IsomorphicLoadedClerk {
return this.#instance;
}

static clearInstance() {
this.#instance = null;
}

get domain(): string {
// This getter can run in environments where window is not available.
// In those cases we should expect and use domain as a string
Expand Down Expand Up @@ -410,6 +414,12 @@ export default class IsomorphicClerk implements IsomorphicLoadedClerk {

public addOnLoaded = (cb: () => void) => {
this.loadedListeners.push(cb);
/**
* When IsomorphicClerk is loaded execute the callback directly
*/
if (this.loaded) {
this.emitLoaded();
}
};

public emitLoaded = () => {
Expand Down

0 comments on commit 4a05f2e

Please sign in to comment.