2

Scenario: I am passing an array from parent LWC to child LWC and looping over it in child component. In child LWC, when a button is clicked, I am trying to add an item at the beginning to the array, but the value is not updating.

childLWC.js

    import { LightningElement, api, track, wire } from 'lwc';
    
    export default class ChildLWC extends LightningElement {
        @api testArray;
    
        get testArrays() {
            return [...this.testArray];
        }
    
        handleButtonClick(){
          let arr = ['somevalue'];
          testArrays.unshift(arr); 
        }
  }

I have used get testArrays, since testArray is the array that is passed from parent LWC and hence decorated with api

get testArrays() {
  return [...this.testArray];
}
2

You cannot update an api value from within the component. Either pass the value to the parent component so it can update the array, or use an actual copy of the array:

import { LightningElement, api, track, wire } from 'lwc';

export default class ChildLWC extends LightningElement {
    @track testArrays;
    @api
    get testArray() {
        return this.testArrays;
    }
    set testArray(value) {
        this.testArrays = [...value];
    }
    handleButtonClick() {
        let arr = 'somevalue';
        this.testArrays.unshift(arr);
    }
}

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.