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

refactor: premount loader - 2 #769

Merged
merged 12 commits into from
Nov 7, 2024
Merged
50 changes: 31 additions & 19 deletions src/Payments/PreMountLoader.res
Original file line number Diff line number Diff line change
@@ -1,30 +1,42 @@
let sendPromiseData = (promise, key) => {
open Promise
promise
->then(res => resolve(res))
->catch(_ => resolve(JSON.Encode.null))
->thenResolve(response => {
let executePromise = async () => {
let response = try {
await promise
} catch {
| _ => JSON.Encode.null
}
Utils.messageParentWindow([("response", response), ("data", key->JSON.Encode.string)])
})
->ignore
}
executePromise()->ignore
}

let useMessageHandler = getPromisesAndMessageHandler => {
React.useEffect0(() => {
let (promises, messageHandler) = getPromisesAndMessageHandler()
let useMessageHandler = getPromisesAndHandler => {
React.useEffect(_ => {
let (promises, messageHandler) = getPromisesAndHandler()
let setupMessageListener = _ => {
Utils.messageParentWindow([("preMountLoaderIframeMountedCallback", true->JSON.Encode.bool)])
Window.addEventListener("message", messageHandler)
}

open Promise
Promise.all(promises)
->thenResolve(_ => {
let cleanupMessageListener = _ => {
Utils.messageParentWindow([("preMountLoaderIframeUnMount", true->JSON.Encode.bool)])
Window.removeEventListener("message", messageHandler)
})
->ignore
}

setupMessageListener()

let executeAllPromises = async () => {
try {
let _ = await Promise.all(promises)
} catch {
| error => Console.error2("Error in message handler:", error)
}
cleanupMessageListener()
}
executeAllPromises()->ignore

Utils.messageParentWindow([("preMountLoaderIframeMountedCallback", true->JSON.Encode.bool)])
Window.addEventListener("message", messageHandler)
Some(() => Window.removeEventListener("message", messageHandler))
})
Some(cleanupMessageListener)
}, [])
}

module PreMountLoaderForElements = {
Expand Down
Loading