Sunday, 14 June 2020

ES6 Spread Notation for LWC


The spread operator is three dots (...) preceding an array.
The spread operator is a new way to add elements to an array without mutating.

Push Vs Spread 

push    - mutates the original data.
spread  - does not mutate the original data.


<template>
  <lightning-card title="HelloWorld" icon-name="custom:custom14">
      <div class="slds-m-around_medium">
          <template for:each={contacts} for:item="contact">
              <li key={contact.id}>
                  {contact.name}, {contact.title}
              </li>
          </template>
          <lightning-button variant="base" label="Base" title="Base action" onclick={handleClick} class="slds-m-left_x-small"></lightning-button>
      </div>
  </lightning-card>
</template>


import { LightningElement, track } from 'lwc';

export default class HelloWorld extends LightningElement {
    @track contacts = [
        {
            id: 1,
            name: 'Amy Taylor',
            title: 'VP of Engineering',
        },
        {
            id: 2,
            name: 'Michael Jones',
            title: 'VP of Sales',
        },
        {
            id: 3,
            name: 'Jennifer Wu',
            title: 'CEO',
        },
    ];
    lastId = 3;
    
    handleClick() {
        const id = this.lastId + 1;
        const contact = {
            id,
            name: 'New Name',
            title: 'New Title',
        };
        this.lastId = id;
        this.contacts = [...this.contacts, contact];
    }
}


Note : 
1.Recreates the array with the new value.
2.Refreshes reactive variables the same way a @track variable does when changing its value.


ex 2 :

<template>
    
    <lightning-datatable
                key-field="id"
                data={data}
                columns={columns}
                is-loading={tableLoadingState}>
            </lightning-datatable>

 <lightning-button variant="brand" label="Add row" title="Add row" onclick={addRow} class="slds-m-left_x-small"></lightning-button>
</template>

import { LightningElement, track } from 'lwc';
const columns = [
    { label: 'Label', fieldName: 'name', type:"text"},
    { label: 'Website', fieldName: 'website', type: 'text' },
    { label: 'Phone', fieldName: 'phone', type: 'text'  }
];
export default class App extends LightningElement {
    @track data = [{name:'Mylabel' , website:'google.com' ,phone :'74126478963',amount : 45  }];
    @track columns = columns;
    @track tableLoadingState = false;

    addRow(){
          const newdata = {            
            name: 'Mylabel2s',
            website:'2google.com',
phone :'74126478963',
amount : 45
        };  
      // spread Operator
        this.data = [...this.data ,newdata ];

    }
   
}

No comments:

Post a Comment