I have a LWC which takes value from 3 input fields and passes the value to a separate component with lightning datatable via LMS. I am able to pass the data for the first time but when I try to repeat the process all the values in the array are updated to the latest value.
Publisher Component HTML:
<template>
<lightning-card title="Input Data">
<lightning-input class="slds-m-around_medium" type="text" data-id="name" label="Enter Name" onchange={inputHandler}></lightning-input>
<lightning-input class="slds-m-around_medium" type="text" data-id="phone" label="Enter Phone" onchange={inputHandler}></lightning-input>
<lightning-input class="slds-m-around_medium" type="text" data-id="country" label="Enter Country" onchange={inputHandler}></lightning-input>
<lightning-button class="slds-m-around_medium" label="Send Data" variant="brand" onclick={dataHandler}></lightning-button>
</lightning-card>
</template>
Publisher Component JS:
import { LightningElement, wire } from 'lwc';
import { publish, MessageContext } from 'lightning/messageService';
import SEND_MESSAGE from '@salesforce/messageChannel/Send_Message__c';
export default class DataFiller extends LightningElement {
name;
phone;
country;
@wire(MessageContext)
messageContext;
records=[];
data={};
inputHandler(event){
if(event.target.dataset.id == 'name'){
this.name = event.target.value;
this.data.Name = this.name;
console.log(this.data);
}
else if(event.target.dataset.id == 'phone'){
this.phone = event.target.value;
this.data.Phone = this.phone;
console.log(this.data);
}
else{
this.country = event.target.value;
this.data.Country = this.country;
console.log(this.data);
}
}
dataHandler(){
this.records.push(this.data);
let payload = this.records;
publish(this.messageContext, SEND_MESSAGE, payload);
}
Subscriber Component HTML:
<template>
<lightning-card title="Person Details">
<lightning-datatable columns={columns} key-field="Id" data={data}>
</lightning-datatable>
</lightning-card>
</template>
Subscriber Component JS:
import { LightningElement, wire } from 'lwc';
import { subscribe, MessageContext } from 'lightning/messageService';
import SEND_MESSAGE from '@salesforce/messageChannel/Send_Message__c';
export default class PersonTable extends LightningElement {
columns = [{ label : 'Name', fieldName: 'Name'},
{ label : 'Phone', fieldName: 'Phone'},
{ label : 'Country', fieldName: 'Country'}];
data;
subscription=null;
@wire(MessageContext)
messageContext;
subscriptionToMessageChannel(){
this.subscription=subscribe(this.messageContext, SEND_MESSAGE, (messageToSend) => this.handleMessage(messageToSend));
}
connectedCallback(){
this.subscriptionToMessageChannel();
console.log('Subscribed');
}
handleMessage(messageToSend){
this.data = messageToSend;
console.log(JSON.stringify(this.data))
}
}