0

I try to assign a new value (string + var) to a array field. I did a shallow copy, but still receive the mentioned error. Any idea what I'm doing wrong? Thx !!

import { LightningElement, wire } from 'lwc';
import initMethod from "@salesforce/apex/MCWrapperController.initMethod";

export default class Carousel extends LightningElement {
  results;
  
  @wire(initMethod, { cmsContentType: 'cms_image', cmsTopic: 'Home' }) 
  
  getResults(response) {
    const {data, error} = response;

    if (data) {
      arrCopy = [...data];
      arrCopy.forEach(imgUrl => {
        // I try to assign a string and a var, eg ... = "https://..." + {url}
        imgUrl.contentNodes.source.url = "string" // for testing only string
      });
      this.results = arrCopy;
      
      console.log ('cms', this.results);
     } else if (error) {
      // handle error
    }
  }
}

1 Answer 1

1

The thing is, that shallow copy only changes first level, but deeper levels are still wrapped into readonly proxy, so I recommend doing like this

 getResults(response) {
    const {data, error} = response;

    if (data) {
      this.results = data.map(item => Object.assign({}, item, {
        contentNodes: {
          source: {
            url: 'string'
          }
        }
      }));

      console.log ('cms', this.results);
    } else if (error) {
      // handle error
    }
  }

so you create a separate object and do not modify returned from the Apex.

Not sure about this deep assignment, you might want to do it via separate variable, but Object.assign will do it's job const tmp= Object.assign({}, item)

UPDATE

This deep assignment doesn't work, one minute, I'll update to the option with additional variable

UPDATE2 this deep properties are sad( Either just JSON.parse(JSON.stringify)) or set it somewhere else

1
  • you put me in the right direction. I went for JSON.parse(JSON.stringify)) and used than a forEach to modify the fields. Works perfect now and reminded me to learn more about the security concept.
    – Maserick
    Mar 30, 2021 at 16:13

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .