Skip to content

Commit

Permalink
fix/BasisTheoryReact initializing multiple times when rerender
Browse files Browse the repository at this point in the history
  • Loading branch information
talberkoMelio authored and kevinperaza committed Feb 16, 2024
1 parent 57cdada commit 227af38
Showing 1 changed file with 6 additions and 2 deletions.
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

0 comments on commit 227af38

Please sign in to comment.