Description
For example, in an app I'm trying to use this in, neither of these logs work:
class MyEl extends ConsumerMixin(Element) {
contexts = {
'foo-context': (foo) => console.log('foo: ', foo) // this never fires
}
connectedCallback() {
super.connectedCallback()
console.log('foo: ', this.getContext('foo-context')) // logs 'undefined' instead of the expected value
}
}
but this works:
class MyEl extends ConsumerMixin(Element) {
connectedCallback() {
super.connectedCallback()
setTimeout(() => {
// this works because by this time the higher-up provider is ready to provide (its connectedCallback has already ran)
console.log('foo: ', this.getContext('foo-context')) // logs the expected value
}, 1000)
}
}
What we need to do is improve the pattern so that it can work regardless of upgrade orde, which I know, is very tricky!
Without a solution, the class-declarative API (contexts = {}
) is not usable, and we have to resort to always calling getContext()
after a delay to ensure that it always works no matter when or how end users of our elements might load those elements.
It is worth noting too, that regardless of upgrade order, the browser also calls connectedCallback
in differing order (children first then parent, or parent first then children) depending on scenario, which just makes things tricky. There's just no actual guaranteed order that callbacks will fire, even if all elements are defined ahead of time.