2

I recently ran into a problem using Charts JS in Lightning web components. I wanted to share a solution I found for those who run into problems

How to manually handle data changes in a child component when they are updated on the parent. This will work with everything but I was trying to update the Chartsjs example they show.

1 Answer 1

3

This is the solution I came up with.

The parent Controller Has the following nested function

@wire(getRecord, { recordId: '$recordId', fields: CONTACT_FIELDS })
wireContact({ error, data }) {
    if (data) {
        console.log('getRecord Data', JSON.stringify(data))
        this.contact = data;
        getAllDateRecords({ contactId: this.recordId })
            .then(result => {
                this.allDateRecords = result;
                this.chartReady = true;
            })
            .catch(err => console.log(JSON.stringify(err)));
    } else if (error) {
        console.error('error', error)
        this.contact = undefined;
    }

}

The Parent Component has c-debt-chart component andd its receiving data from the all-date-records:

<template>
<div class="slds-page-header__row slds-accordion__content">
                <div class="c-container w-100">
                    <lightning-layout horizontal-align="space">
                        <lightning-layout-item padding="around-small">
                            <template if:true={chartReady}>
                                <c-debt-chart all-date-records={allDateRecords}></c-debt-chart>
                            </template>
                        </lightning-layout-item>
                    </lightning-layout>
                </div>
            </div>
<template>

The Problem was that the examples on Salesforce dont show how to update the data in charts js. This is the solution I found using Getter and Setters

Child Component debt chart

<template>
    <lightning-card title="Debt Overview" icon-name="standard:currency">
        <div class="slds-m-around_medium">
            <canvas class="donut" lwc:dom="manual"></canvas>
        </div>
    </lightning-card>
</template>

Debt Chart Controller

Every Time the variable allDateRecords changes at the parent level. It will trigger the child to update using the getter setter methods. This way on the setter method it will fire the seperateDateObject function which does some logic to update the chart.

@api
get allDateRecords() {
    return this._allDateRecords;
}

set allDateRecords(value) {
    this._allDateRecords = value;
    this.separateDateObject();
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.