CWCO logo

v1.7.9

onUpdate

This livecycle function is called right after the DOM gets updated by a property, observed attribute or context is change.

Differently than the attributeChangedCallback, the onUpdate will only get called if the component is mounted. The attributeChangedCallback can also be called before the connectedCallback in case the tag has observed attributes. That does not happen with onUpdate.

It will always get called with the name of the property that changed, the old and the new value as arguments.

class BFSButton extends WebComponent {
	static observedAttributes = ['label']
	
	onUpdate(prop, oldValue, newValue) {
		console.log('updated', prop, oldValue, newValue)
	}
}

BFSButton.register();
const btn = new BFSButton();

// will not trigger onUpdate call
// because the component is not in the DOM yet
btn.label = 'sample';

// will trigger onMount call
document.body.appendChild(btn)

// will trigger onUpdate call and DOM update
btn.label = 'another';
btn.setAttribute('label', 'another');

// will trigger onDestroy call
btn.remove()

In other libraries and frameworks, the update livecycle is often called after the first render but not with CWCO.

If onUpdate is called, the following is True:

  1. A property, attribute or context was changed.
  2. The DOM elements already got updated with the changes.

So onUpdate is more like a afterComponentUpdate and CWCO offers no lifecycles for before the component updates. You can achieve that by combining setters and forceUpdate if you really need such feature.

class CountUpButton extends WebComponent {
	#count = 0;
	
	get count() {
		return this.#count;
	}
	
	set count(val) {
		this.#count = val;
		this.forceUpdate(); // won't trigger onUpdate
	}

	get template() {
		// you need the "this" keyword to access getters
		return '<button type="button">{this.count}</button>'
	}
}
Note: We strongly advice against using the forceUpdate. You should avoid it as much as possible. We plan on supporting setters to trigger DOM updates in the near future.