0

I need to generate columns dynamically based on input target property component, But its making duplicate columns when you navigate to new record pages.

<template>
        <lightning-datatable
                key-field="id"
                hide-checkbox-column
                data={data}
                columns={columns}>
        </lightning-datatable>
</template>

Js:

import { LightningElement,api } from 'lwc';
const COLUMNS = [{label: 'Id', fieldName: 'id'},
                 {label: 'Name', fieldName: 'name'}];
export default class TestlwcDataTable extends LightningElement {
    columns=COLUMNS;
    data;
    @api fields='roll,staff';

    connectedCallback() {
        this.setColumns();
        this.setData();
    }

    async setColumns() {
        const cols = COLUMNS;
        this.fields.split(',').forEach((field) => {
            cols.push({label: field, fieldName: field});
        });
        this.column = cols;
    }

    async setData() {
        this.data=[{id: '1', name: 'Anand', roll:'CEO',staff: 'yes'},
                   {id: '2', name: 'Bala', roll:'CFO',staff:'no'},
                   {id: '3', name: 'Chandru', roll:'EEO',staff:'yes'}];
    }
}

First time its working without duplicate then when ever I open new record its duplicating columns.

enter image description here

I know we can use map to check unique before pushing column, but I need to know weather it is salesforce issue or expected behaviour ?

1 Answer 1

1

This is why you shouldn't be using forEach/push. Each time the method is called, the duplication occurs. Instead, use map:

this.column = this.fields.split(',').map(
  (field) => ({ label: field, fieldName: field })
);

This overwrites the previous values so they are consistent with the fields property.

2
  • 1
    Thanks @sfdxfox for your answer, why is that connectedCallback() is been call twice with holding previous values ? Is it the expected behaviour when we navigate to different record page ?
    – Ragul
    Sep 23 at 21:39
  • 2
    @Ragul The Lightning Experience (LEX) can reuse components, which improves performance. As such, a typical component in LEX may go through several connectedCallback/disconnectedCallback cycles. Components are only finally released when some (undocumented) conditions are met. You should never assume your component can only connect and disconnect once.
    – sfdcfox
    Sep 23 at 21:58

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .