reactjstwilio

Don't know the right way to import taskrouter.js into react


I trying to import taskrouter.js into my react app, and I dont know the right way to do it.

 const script = document.createElement("script");
    script.src = "../library/taskrouter.js";
    script.async = true;
    document.body.appendChild(script)
    script.onload = function() {
        axios.get(url_host + '/worker/activiti')
        .then((res) => {
            var worker = new Twilio.TaskRouter.Worker(res);
            console.log("YEET",worker)
        })
      };

This is the error that I get.

Unhandled Rejection (TypeError): Cannot read property 'Worker' of undefined

Solution

  • Twilio developer evangelist here.

    First of all, have you confirmed that loading the script like that does actually include the TaskRouter JS file on your page? I'd be concerned that webpack (or whatever you are using to build your application) might do something unexpected with the script src you're setting there. Or may not ultimately refer to the correct file after the project is built.

    I would try one of two things to include TaskRouter.js. Either include the TaskRouter.js file from the CDN outside of React's control over the application, in the <head> of your index.html file.

    <script src="//media.twiliocdn.com/taskrouter/js/v1.13/taskrouter.min.js"></script>
    

    Alternatively, there is an npm package now available for TaskRouter JS. Use it by installing into your project:

    npm install twilio-taskrouter --save
    

    You can then use the worker from React by importing it like so:

    import { Worker } from 'twilio-taskrouter';
    

    You can then instantiate a new worker using:

    const worker = new Worker(token);
    

    Let me know if that helps at all.