Created
November 5, 2022 21:36
-
-
Save david-mateogit/6cef3abf9472bbbaf8ff2fe125149b72 to your computer and use it in GitHub Desktop.
Custom hook to load a MercadoPago Script and attach it to an element.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useEffect, useState } from "react"; | |
export const useMercadoPago = (preferenceId, divEl) => { | |
const [status, setStatus] = useState(preferenceId ? "loading" : "idle"); | |
useEffect(() => { | |
const divContainer = document.getElementById(divEl); | |
let script = divContainer.querySelector("script"); | |
if (!preferenceId) { | |
setStatus("idle"); | |
return; | |
} | |
if (!script) { | |
script = document.createElement("script"); | |
script.type = "text/javascript"; | |
script.src = "https://www.mercadopago.cl/integrations/v1/web-payment-checkout.js"; | |
script.async = true; | |
script.setAttribute("data-preference-id", `${preferenceId}`); | |
script.setAttribute("data-status", "loading"); | |
script.setAttribute("data-source", "button"); | |
script.setAttribute("data-button-label", "Comprar Ticket"); | |
divContainer.appendChild(script); | |
const setAttributeFromEvent = (event) => { | |
script.setAttribute("data-status", event.type === "load" ? "ready" : "error"); | |
}; | |
script.addEventListener("load", setAttributeFromEvent); | |
script.addEventListener("error", setAttributeFromEvent); | |
} else { | |
setStatus(script.getAttribute("data-status")); | |
} | |
const setStateFromEvent = (event) => { | |
setStatus(event.type === "load" ? "ready" : "error"); | |
}; | |
script.addEventListener("load", setStateFromEvent); | |
script.addEventListener("error", setStateFromEvent); | |
return () => { | |
if (script) { | |
script.removeEventListener("load", setStateFromEvent); | |
script.removeEventListener("error", setStateFromEvent); | |
script.parentNode.removeChild(script); | |
} | |
}; | |
}, [divEl, preferenceId]); | |
return status; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment