1

I am getting error when I try to clear out array selectedCaseComments in showFeedDetail method called from connectedCallback and caseComments and prevSelectedCommentId are getting populated from parent component.

js file

import { LightningElement, api, track } from 'lwc';
export default class LwcTspNotificationPage extends LightningElement {
    @api caseComments;
    @api prevSelectedCommentId;
    @track selectedCaseComments = [];
}

  connectedCallback() {
        Promise.resolve().then(() => {
             this.showFeedDetail(this.prevSelectedCommentId);
        });
}

showFeedDetail(selectedCommentId){
        let caseFeed = this.caseComments.filter(cseComment => {return cseComment.Id === selectedCommentId});
        if('caseComments' in caseFeed[0]){
            this.selectedCaseComments = caseFeed[0].caseComments;
        } else {
            this.selectedCaseComments.length = 0;
        }
}

let caseFeed = this.caseComments.filter(cseComment => {return cseComment.Id === selectedCommentId}); this gives result like below: enter image description here

As shown in the image if there is no property named caseComments in the array, I am trying to clear out this.selectedCaseComments.length = 0;, this gives error

Uncaught (in promise) TypeError: 'set' on proxy: trap returned falsish for property 'length'
1

You can't modify incoming data from an @api variable. This happens when you first assigned caseFeed to a value from this.caseComments, then later access this.selectedCaseComments to try and modify that array. You need to either copy the original array, or just create a new array.

Copy Array

this.selectedCaseComments = [...caseFeed[0].caseComments];

Create New Array

this.selectedCaseComments.length = [];

JavaScript passes objects by reference unless you copy the object, but the original object was read-only. You can see that effect with this code:

var x1 = { y: { z: 5 } }
var x2 = x1.y;
x2.z = 10;
console.log(x1.y.z); // outputs 10, not 5.

To fix this problem, you'd also do the same thing (but with an object):

var x1 = { y: { z: 5 } }
var x2 = { ...x1.y }
x2.z = 10;
console.log(x1.y.z); // Outputs 5
console.log(x2.z); // Outputs 10

Note that ... is a shallow copy, so if you need to access any further child elements, those must also be copied somehow.

1
  • Thanks! I went ahead with ... to create a copy of original array. – devforce Jul 20 '20 at 12:43

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.