Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: prevents multiple init calls during re-renders #232

Merged
merged 1 commit into from
Feb 16, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
fix/BasisTheoryReact initializing multiple times when rerender
  • Loading branch information
talberkoMelio authored and kevinperaza committed Feb 16, 2024
commit 227af38145a55ff3c4406efd2b4975445d4c5c16
8 changes: 6 additions & 2 deletions src/core/useBasisTheory.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useEffect, useState } from 'react';
import { useEffect, useState, useRef } from 'react';
import type {
BasisTheoryInitOptionsWithElements,
BasisTheoryInitOptionsWithoutElements,
Expand Down Expand Up @@ -35,13 +35,15 @@ function useBasisTheory(
| BasisTheoryInitOptionsWithoutElements
): UseBasisTheory<boolean> {
const [state, setState] = useState<UseBasisTheory<boolean>>({});
const isLoading = useRef(false);

const { bt: btFromContext } = useBasisTheoryFromContext();

useEffect(() => {
(async (): Promise<void> => {
if (!state.bt && apiKey && !state.error) {
if (!state.bt && apiKey && !state.error && !isLoading.current) {
try {
isLoading.current = true;
const bt = (await new BasisTheoryReact().init(
apiKey,
options as BasisTheoryInitOptionsWithElements &
Expand All @@ -55,6 +57,8 @@ function useBasisTheory(
setState({
error: error as Error,
});
} finally {
isLoading.current = false;
}
}
})();
Expand Down
Loading