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

feat: use new useDynamicScript hook in HostedForm #12

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

obsoke
Copy link

@obsoke obsoke commented Apr 4, 2024

Fixes #5.

Explanation

The problem: The dynamic nature of React means components will be loaded & unloaded from the DOM as a user navigates a single-page application.

The docs for Accept.js state:

If you are building your page dynamically, be sure that your page loads the Accept JavaScript library after the button is defined. For the library to correctly interface with the button, the button must already exist in the DOM when the library is loaded.

This requirement is most likely due to needing to attach an event listener to the button to launch the hosted form. When a user navigates to another part of the SPA that unloaded <HostedForm />, that event listener breaks.

The (admittedly hacky) solution is to remove AcceptUI.js from the DOM when <HostedForm /> is unloaded. Navigating back to the page with the <HostedForm /> will add the script back to the DOM, allowing usage of <HostedForm /> without a hard refresh.

Changes

A new hook, useDynamicScript(), was added. It's similar to useScript() but will remove the <script> tag containing AcceptUI.js when the component containing the hook is unloaded.

Caveats

The initial plan was to fetch() the script so we could inject the script text into a <script> tag ourselves to prevent additional network requests. However, the lack of any CORS policy defined on https://js.authorize.net prevents this.

The script itself is only 5.8KB so it shouldn't be too painful to reload the script for each usage.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

HostedForm is not showing up
1 participant