1

I am trying to follow this documentation to create a D3 Simple Bar graph in my web component. At the very bottom you will see the section Other Useful Patterns followed by a piece on how to load a script resource. In enter link description here they say you n need to load this script in order to use the scaleBand method for Bar Graphs:

<script src="https://d3js.org/d3-selection-multi.v1.min.js"></script>

So, what I attempted to do was put this in my JS file:

import { LightningElement } from 'lwc';
import { loadScript, loadStyle } from 'lightning/platformResourceLoader';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import D3 from '@salesforce/resourceUrl/D3JavaScript';

export default class YtpReport extends LightningElement {
    svgWidth = 400;
    svgHeight = 400;

    d3Initialized = false;

    loadScript(this, D3 + '/d3-selection-multi.v1.min.js').then(() => {});

    ...
}

But I get the unexpected token error on the 15th column of the loadScript line...

How are you suppose to load this kind of resource?

1 Answer 1

3

You will need to load the scripts in the renderedCallback() Lifecycle Hook. From documentation:

renderedCallback() {
    if (this.d3Initialized) {
        return;
    }
    this.d3Initialized = true;

    Promise.all([
        loadScript(this, D3 + '/d3.v5.min.js'),
        loadStyle(this, D3 + '/style.css'),
    ])
    ...
}

At least in Lightning Aura Component framework, the scripts are loaded asynchronously and they may not be available when the component is being rendered, thus its always loaded after the component has been rendered. I would imagine the same to be true for LWC as well, and thus renderedCallback() needs to be utilized here.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.