Otavio Bonder
Otavio Bonder

Reputation: 1999

Call JS function on script tag

I'm trying to implement Trulioo to a React application. Their documentation tells to put a <script> tag on the page, which will render their application form:

<div id="trulioo-embedid"></div>

<!-- This script renders the form for the div above --> 
<script type="text/javascript" src="https://js.trulioo.com/latest/main.js"></script>

<!-- Initialize your form here with your Frontend (FE) key -->
<script> 
  // Handle the response of EmbedID after form submits
  function handleResponse(e) { 
    console.log('handleResponse', e); 
  } 
  
  const publicKey = 'Trial Key (FE)_OR_Live Key (FE)'; // Public Key
  // const accessTokenURL = 'http://localhost:8080/trulioo-api/embedids/tokens';
  new TruliooClient({ 
    publicKey, 
    // accessTokenURL,
    handleResponse 
  });
</script>

I implemented it the React way:

import React, { useEffect } from 'react';
import truliooConfig from '../../../config/tuliooConfig';

export default function CustomerSignup() {
    function handleResponse(e) {
        console.log(e);
    }
    const { publicKey, accessTokenURL } = truliooConfig;

    useEffect(() => {
        const script = document.createElement('script');
        script.src = 'https://js.trulioo.com/latest/main.js';
        script.async = true;

        document.body.appendChild(script);

        /*new TruliooClient({
            publicKey,
            accessTokenURL,
            handleResponse,
        });*/

        return () => {
            document.body.removeChild(script);
        };
    }, []);

    return <div id="trulioo-embedid" />;
}

The script loads fine and it's appended to the DOM, but I need to call the new TruliooClient({}) with the authentication parameters.

I'm not sure how to call it, since it's not defined in React.

How can I solve this issue?

Thanks in advance

Edit: adding

script.onload = function () {
            new TruliooClient({ publicKey: publicKey, accessTokenURL: accessTokenURL, handleResponse });
        };

won't work either, because TruliooClient is not defined, even though it is defined in the script

Upvotes: 2

Views: 165

Answers (1)

Otavio Bonder
Otavio Bonder

Reputation: 1999

Okay, to anybody looking for an answer to the same problem, I could make it work.

I had to create a function to execute after the script was loaded:

    function scriptLoaded() {
        new window.TruliooClient({
            publicKey,
            accessTokenURL,
            handleResponse,
        });
    }

And I called it inside the useEffect:

    useEffect(() => {
        const script = document.createElement('script');
        script.src = 'https://js.trulioo.com/latest/main.js';
        script.async = true;
        script.onload = () => scriptLoaded();

        document.body.appendChild(script);

        return () => {
            document.body.removeChild(script);
        };
    }, []);

Upvotes: 2

Related Questions