Skip to content

[reactive-element] Avoid @query caching null results before the first render #4237

@MaxArt2501

Description

@MaxArt2501

Should this be an RFC?

  • This is not a substantial change

Which package is this a feature request for?

Lit Core (lit / lit-html / lit-element / reactive-element)

Description

If you access @queryd property before the first render, if will yield null but will stay null is you set the cache flag to true. The documentation should probably warn the users that this might happen (might open a separate issue on lit.dev repo).

I think it could be beneficial if @query caches the result only if it actually has a chance to return a non-null result, i.e. only if hasUpdated is true. Something like this:

descriptor.get = function (this: ReactiveElement) {
  // No caching here
  if (!this.hasUpdated) return null;
  // Rest of the getter code...
};

I'm available to open a PR for this.

Alternatives and Workarounds

No alternative that would be as simple as using @query straight away.

One could redefine their own @query selector, but of course it'd need to be kept in line with Lit's decorator.

Alternatively, one could check if hasUpdated is true if they need to access the queried property. A secondary getter could be handy, but adds overhead:

class MyElement extends LitElement {
  @query('button', true) private _button!: HTMLButtonElement | null;

  get button() {
    return this.hasUpdated ? this._button : null;
  }
  // ...
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    Status

    ✅ Done

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions