diff --git a/CHANGELOG.md b/CHANGELOG.md index a90d456444..7ff7d7603b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## 3.17.3 +* Make autosubscribing to a nullish store a no-op ([#2181](https://github.com/sveltejs/svelte/issues/2181)) * Fix updating a `` inside an `{#if}` or other block ([#4292](https://github.com/sveltejs/svelte/issues/4292)) * Fix using RxJS observables in `derived` stores ([#4298](https://github.com/sveltejs/svelte/issues/4298)) * Add dev mode check to disallow duplicate keys in a keyed `{#each}` ([#4301](https://github.com/sveltejs/svelte/issues/4301)) diff --git a/src/runtime/internal/utils.ts b/src/runtime/internal/utils.ts index c7722e1a07..4ba7e18c15 100644 --- a/src/runtime/internal/utils.ts +++ b/src/runtime/internal/utils.ts @@ -43,12 +43,15 @@ export function not_equal(a, b) { } export function validate_store(store, name) { - if (!store || typeof store.subscribe !== 'function') { + if (store != null && typeof store.subscribe !== 'function') { throw new Error(`'${name}' is not a store with a 'subscribe' method`); } } export function subscribe(store, ...callbacks) { + if (store == null) { + return noop; + } const unsub = store.subscribe(...callbacks); return unsub.unsubscribe ? () => unsub.unsubscribe() : unsub; } diff --git a/test/runtime/samples/store-auto-subscribe-nullish/_config.js b/test/runtime/samples/store-auto-subscribe-nullish/_config.js new file mode 100644 index 0000000000..52e21cef05 --- /dev/null +++ b/test/runtime/samples/store-auto-subscribe-nullish/_config.js @@ -0,0 +1,13 @@ +import { writable } from '../../../../store'; + +export default { + html: ` +

undefined

+ `, + async test({ assert, component, target }) { + component.store = writable('foo'); + assert.htmlEqual(target.innerHTML, ` +

foo

+ `); + } +}; diff --git a/test/runtime/samples/store-auto-subscribe-nullish/main.svelte b/test/runtime/samples/store-auto-subscribe-nullish/main.svelte new file mode 100644 index 0000000000..9c1ed4a560 --- /dev/null +++ b/test/runtime/samples/store-auto-subscribe-nullish/main.svelte @@ -0,0 +1,5 @@ + + +

{$store}