1

We have a JavaScript utility class containing two properties, like:

class DateRange {
    start;
    end;

    constructor(start, end) {
        this.start = dateToIsoDateLocal(start instanceof Date ? start: isoDateToLocal(start));
        this.end = dateToIsoDateLocal(end instanceof Date ? end: isoDateToLocal(end));
    }
}

We then have a component that has a tracked property of this type, accompanied by a function for accessing this outside the component:

@track dateRange;

@api getDateRange() {
    return this.dateRange;
}

When a parent component tries to access this tracked property using the getDateRange function we get an error of the form:

Uncaught (in promise) Error: Access denied: {"from":{"namespace":"someNS"},"to":{"namespace":"default"}}

Both components (the one holding the DateRange property and the one trying to access it) are in the same namespace. Why are we getting this error?

2

The problem appears to relate to the way tracked parameters are implemented using a Proxy, with this then covered by/using the locker service in order to apply security constraints.

The error is misleading but essentially the getDateRange API function is returning internal state of the child component, by reference. It looks like the handling of "standard" types (such as primitives) is catered for in the LWC component infrastructure, but this doesn't extend to "custom" JavaScript classes.

The solution is to update the getter method, thus:

@api getDateRange() {
    // We can't return the tracked property since it has internal scope, we have
    // to return a new instance derived from it
    return this.dateRange ?
            new DateRange(this.dateRange.start, this.dateRange.end) :
            undefined;
}

In doing this we ensure that the returned object is not a proxy but rather an instance of the JavaScript class itself.

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.