Skip to content

fix: recreate instance immediately #350

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

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
33 changes: 16 additions & 17 deletions src/usePlaidLink.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useEffect, useState } from 'react';
import { useEffect, useMemo, useState } from 'react';
import useScript from 'react-script-hook';

import { createPlaid, PlaidFactory } from './factory';
Expand Down Expand Up @@ -29,14 +29,13 @@ export const usePlaidLink = (options: PlaidLinkOptions) => {
});

// internal state
const [plaid, setPlaid] = useState<PlaidFactory | null>(null);
const [iframeLoaded, setIframeLoaded] = useState(false);
const products = ((options as PlaidLinkOptionsWithPublicKey).product || [])
.slice()
.sort()
.join(',');

useEffect(() => {
const plaid = useMemo((): PlaidFactory | void => {
// If the link.js script is still loading, return prematurely
if (loading) {
return;
Expand All @@ -57,27 +56,16 @@ export const usePlaidLink = (options: PlaidLinkOptions) => {
return;
}

// if an old plaid instance exists, destroy it before
// creating a new one
if (plaid != null) {
plaid.exit({ force: true }, () => plaid.destroy());
}

const next = createPlaid(
return createPlaid(
{
...options,
onLoad: () => {
setIframeLoaded(true);
setIframeLoaded(false);
options.onLoad && options.onLoad();
},
},
window.Plaid.create
);

setPlaid(next);

// destroy the Plaid iframe factory
return () => next.exit({ force: true }, () => next.destroy());
}, [
loading,
error,
Expand All @@ -86,7 +74,18 @@ export const usePlaidLink = (options: PlaidLinkOptions) => {
products,
]);

const ready = plaid != null && (!loading || iframeLoaded);
useEffect(() => {
setIframeLoaded(false);
if (!plaid) {
return;
}
return () => {
// destroy the Plaid iframe factory when unmounting an instance
plaid.exit({ force: true }, () => plaid.destroy());
}
}, [plaid])

const ready = !!plaid && !loading && iframeLoaded;
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This was previously

const ready = plaid != null && (!loading || iframeLoaded);

But reading that code, it seems to me that iframeLoaded is completely unused - it can't be true without being first loading === true, so I'm guessing this fixes some edge-case bug


const openNoOp = () => {
if (!options.token) {
Expand Down