feat: use new useDynamicScript hook in HostedForm #12
+58
−2
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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:
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 touseScript()
but will remove the<script>
tag containingAcceptUI.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 onhttps://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.