this script is created and injected correctly but not execute when try to instance it, but rightly works from browser console.
useEffect(() => {
const script = document.createElement('script');
script.id = 'mp';
script.type = 'text/javascript';
script.src = 'https://sdk.mercadopago.com/js/v2';
document.body.appendChild(script);
const mp = new window.MercadoPago('PUBLIC-KEY', {
locale: 'es-AR'
});
mp.checkout({
preference: {
id: '489283197-ac01a776-5696-46ff-a300-98853bd3472d'
},
render: {
container: '.mp-test',
label: 'Pagar',
}
});
}, [])
ERROR: window.MercadoPago is not constructor capture error
I hope suggestes, thanks
You are 90% right on your code. The problem is that you are trying to use the script before it's finished downloading. On a side note, remember to remove the the script from the page when you leave (unmount) the component.
const [mercadoPagoLoaded, setMercadoPagoLoaded] = useState(false)
useEffect(() => {
const script = document.createElement('script')
script.src = 'https://sdk.mercadopago.com/js/v2'
script.async = true // since it's an external resource, you need to execute it after it's downloaded.
script.onload = () => {
// Execute library related code after it has been loaded
const publicKey = process.env.REACT_APP_MERCADOPAGO_PUBLIC_KEY
window.MercadoPago = new window.MercadoPago(publicKey)
window.MercadoPago.key = publicKey
setMercadoPagoLoaded(true) // If you have dependencies, set its state as loaded.
}
document.body.appendChild(script)
return () => {
document.body.removeChild(script)
delete window.MercadoPago
}
}, [])
useEffect(() => {
if (mercadoPagoLoaded) {
// ... Code dependent on the Library
}
}, [mercadoPagoLoaded])