When attempting to click the "New" button in a lightning datatable to add a new row, an error

Having trouble adding a new row when clicking the New Button in a Lightning Data table. I've created a lightning-button in HTML and called the method in JavaScript. However, when I click the New button, I'm getting an error message saying Undefined.

 **CustomComponent.html:**

    <template>
    <lightning-card >
    <lightning-button-group>
          <lightning-button label="New" onclick={addRow}></lightning-button>
    </lightning-button-group>
    <lightning-datatable data={strpData} columns={columns} onsave={saveHandleAction}
      draft-values={fldsItemValues} key-field="Id" onrowselection={getSelectedRows}>
         </lightning-datatable>
    </lightning-card >
    </template>
    
**CustomComponent.JS:**

import { LightningElement, track, api, wire } from 'lwc';
const columns = [
    {label:'NUMBER', fieldName:'Name' },
    {label: 'Test1', fieldName: 'Test1'}
];
export default class CustomComponent extends LightningElement {
@track columns = columns;
@track strpData = [];
addRow() {  
       // this.isShowModal = true;
       console.log('>>>adding row>>>');
        const newRow ={'Name':'','Test1':''};
        console.log('>>>new row>>>'+this.newRow);
        this.strpData.push(newRow);
        console.log('strpData ==>>> '+JSON.stringify(strpData));
    }
}

Encountering a console log error during this process:

https://i.sstatic.net/tvqgm.png

Appreciate any assistance with this issue. Thank you.

Answer №1

In order to update the strpData attribute, you must refrain from using the .push() method. Instead, it is necessary to completely "replace" the existing data.

import { LightningElement, track, api, wire } from 'lwc';
const columns = [
    {label:'NUMBER', fieldName:'Name' },
    {label: 'Test1', fieldName: 'Test1'}
];
export default class Test extends LightningElement {
@track columns = columns;
@track strpData = [];
addRow() {  
       // this.isShowModal = true;
       console.log('>>>add row>>>');
        const newRow ={'Name':'','Test1':''}; 
        console.log('>>>new row>>> '+this.newRow);
        this.strpData = [...this.strpData, newRow];
        console.log('strpData ==>>> '+JSON.stringify(strpData));
    }
}

Check here for more information

Answer №2

newRow is defined as a const, not a class variable. Simply remove the this keyword from your logging statement:

addRow() {  
   // this.isShowModal = true;
    console.log('>>>add row>>>');
    const newRow ={'Name':'','Test1':''};
    console.log('>>>new row>>>'+newRow);
    this.strpData.push(newRow);
    console.log('strpData ==>>> '+JSON.stringify(strpData));
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing React, manipulating the DOM by utilizing getElementById, and then attempting to swap out a node with a React Component

Is there a method to replace a DOM node with a ReactJS node? If so, how can it be achieved? const myComp = <span>hey</span> const elem = document.getElementById('video1') elem.parentNode.replaceChild(myComp, elem) What is the correc ...

Create a CSS menu that centers the links

Here is the CSS code I am using for my horizontal menu: nav { height: 40px; width: 100%; background: #F00; font-size: 11pt; font-family: Arial; font-weight: bold; position: relative; border-bottom: 2px solid # ...

Looking to tweak the date format in a Vue.js template?

I received the following format: 2019-01-08T11:11:00.000Z However, I need it to be in this format: 2019-01-08 Does anyone know how to achieve this date formatting without using the moment package? ...

The graph visualization fails to update properly even after attempting to redraw it

A new feature has been added to the website that allows users to zoom into specific areas of graphs created using Flot objects. An array containing all the Flot objects on the screen has been implemented, and the selection plugin is being used for this pur ...

I'm looking to create a unique combination of a line and bar chart. Any advice on how to

When I stretch my Scale like this determineDataLimits: function () { var min = Math.min.apply(null, this.chart.data.datasets[0].data) console.log(this) console.log(defaultConfigObject) Chart.options.scales.rightSide.ticks.min = function ...

Opposite path matching with Next.js middleware

For my Next.js project, I have implemented a middleware and now I need it to only apply to routes that do not start with /api/. I have checked the documentation but couldn't find a similar example. Is there a way to achieve this without manually excl ...

steps to verify the status of a sent request

I am utilizing the contenteditable property in a p tag. My code is as follows: <p contenteditable="true" id="Option1_<?php echo $i ?>" style="width:98%;border:4px thin black; background-color:#D6D6D6;font-size:18px;color:black;padding:3px ">&l ...

What is the proper way to end a session once an aspx page has been exited?

In a scenario where I have an aspx page that is opened as a popup page using Javascript code, I perform certain actions and store data in a session variable like Session["x"] = data. However, when I close the page, I need to reset Session["x"] to null. H ...

Challenges with inferring return values in Typescript generics

I'm encountering an issue with TypeScript that I'm not sure if it's a bug or an unsupported feature. Here is a Minimal Viable Example (MVE) of the problem: interface ColumnOptions<R> { valueFormatter(params: R): string; valueGette ...

Is there a way to automatically insert page numbers into every internal link on an HTML page?

When in print mode, I want to display links like this: <a href="#targetPage">link</a> but I'd prefer them to appear as: <a href="#targetPage">link (page 11)</a> (assuming the target page is on page 11 in the print preview). ...

Allow for the ability to choose a specific option for every individual line that is echoed in

I have researched several similar questions, but none of them address exactly what I am attempting to achieve. My goal is to use AJAX to fetch a PHP page that will display the contents of a folder on my server. Currently, the files are being listed line by ...

Remove the export statement after transpiling TypeScript to JavaScript

I am new to using TypeScript. I have a project with Knockout TS, and after compiling it (using the Intellij plugin to automatically compile ts to js), this is my sample.ts file: import * as ko from "knockout"; ko; class HelloViewModel { language: Kn ...

An error message pops up when using Next.js with Sass, indicating that a suitable loader is required to handle this file type

I've been struggling to properly wire up my next.js project with SCSS, but no matter what I try, it just won't work. I double-checked my setup for compiling SCSS files, but the error message keeps popping up: /scss/style.scss 1:0 Module parse f ...

Strange appearance of Material UI input field

https://i.stack.imgur.com/az6wt.png Does anyone have an idea why this problem is occurring? When using material UI, the default value and label for the field seem to be overlapping. Below is the code for rendering the fields: {formSchema.map((element, i ...

Issue with Typescript not recognizing default properties on components

Can someone help me troubleshoot the issue I'm encountering in this code snippet: export type PackageLanguage = "de" | "en"; export interface ICookieConsentProps { language?: PackageLanguage ; } function CookieConsent({ langua ...

Is it possible to implement pagination for loading JSON data in chunks in jsGrid?

Currently, I am utilizing jsgrid and facing an issue with loading a JSON file containing 5000 registries into a grid page by page. My goal is to display only 50 registries per page without loading all 5000 at once. Even though I have implemented paging in ...

Encountered an error while attempting to update an object: Unable to read property 'push' of undefined

Encountering an issue while attempting to update an object with additional information, receiving an error message stating 'property \'push\' of undefined'. /*Below is the object model in question:*/ export class Students { ...

Having Trouble with Form Submission Button Across Different Web Browsers

Having some trouble with my form - all fields are properly closed with tags, but when I click the submit button, nothing happens. The page is loaded with code, so here's the link for you to check it out. Unfortunately, right-click is disabled, so ple ...

Update the src attribute in an HTML document

I am looking to dynamically change the size of an image on an HTML page using a dropdown list. Here is my code: <html> <head> </head> <body> <select id="selectbox" name=""> <opti ...

When it comes to entering text in a text input or textarea within a large module in Vue.js, taking

While filling out my large form, I noticed a delay in rendering whenever I typed quickly into the input boxes. <b-form-input v-model="paymentItems.tierStepUPYear" type="text"></b-form-input> ...