Svelte: component.get() can return undefined after component destroyed

Created on 19 Apr 2018  路  5Comments  路  Source: sveltejs/svelte

Since this.get('foo') is deprecated (https://github.com/sveltejs/svelte/pull/1347), I've been working on migrating all usages to let { foo } = this.get().

However I've found that the two aren't exactly equivalent, since this.get() can actually return undefined if the component is destroyed (e.g. because it was called within a requestIdleCallback() or setTimeout() callback).

Throws an error:

<h1>Hello {name}!</h1>
<script>
    export default {
        oncreate() {
            setTimeout(() => this.destroy(), 1000)
            setTimeout(() => {
                let { name } = this.get() // throws
                console.log('name', name)
            }, 2000)
        }
    }
</script>

Doesn't throw an error:

<h1>Hello {name}!</h1>
<script>
    export default {
        oncreate() {
            setTimeout(() => this.destroy(), 1000)
            setTimeout(() => {
                let name = this.get('name') // does not throw
                console.log('name', name)
            }, 2000)
        }
    }
</script>

So far, my workaround has been to do let { foo } = this.get() || {} but it would be nice if it were just automatically wrapped in an empty object so that the two forms were equivalent.

All 5 comments

Related: it would be useful to be able to know within an asynchronous callback whether the component was destroyed or not, without having to attach an on('destroy') listener. (I notice https://github.com/sveltejs/svelte/pull/948 was not merged.)

Can we combine these two problems into a solution? Does component.get() always return undefined after the component has been destroyed?

I'm not sure. What I am sure about is that _if_ the component is destroyed, then component.get() is undefined. I'm not sure where exactly in the lifecycle it gets set to undefined, i.e. if it's right before getting destroyed, right after, etc.

In any case, I would _prefer_ not to have to think about every place in my code where the component might have been destroyed (i.e. to wrap component.get() in a component.destroyed check or similar), but maybe that's not practical.

I also just fell into this.
It would be great to have the way to know if component was destroyed.
Getting undefined within component.get() may be a solution.
Let's keep it

As of 2.1.1, component state reverts to an empty object on destroy, rather than null. We could revisit #948, though I sort of prefer the idea that in a state-driven system you shouldn't ever have to think about whether a component has been destroyed or not.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

1u0n picture 1u0n  路  3Comments

noypiscripter picture noypiscripter  路  3Comments

Rich-Harris picture Rich-Harris  路  3Comments

st-schneider picture st-schneider  路  3Comments

plumpNation picture plumpNation  路  3Comments