diff --git a/src/runtime/internal/utils.ts b/src/runtime/internal/utils.ts index 979b418596..9d48378603 100644 --- a/src/runtime/internal/utils.ts +++ b/src/runtime/internal/utils.ts @@ -69,7 +69,7 @@ export function validate_store(store, name) { export function subscribe(store, ...callbacks) { if (store == null) { for (const callback of callbacks) { - callback(store); + callback(undefined); } return noop; } diff --git a/src/runtime/store/index.ts b/src/runtime/store/index.ts index 09e5b10bd2..13131d4cc0 100644 --- a/src/runtime/store/index.ts +++ b/src/runtime/store/index.ts @@ -165,8 +165,9 @@ export function derived( export function derived(stores: Stores, fn: Function, initial_value?: T): Readable { const single = !Array.isArray(stores); const stores_array: Array> = single - ? [stores as Readable] - : stores as Array>; + // Fall back to readable() for falsy stores in array, else derived store will be forever pending + ? [(stores || readable()) as Readable] + : (stores as Array>).map(store => store || readable()); const auto = fn.length < 2; diff --git a/test/store/index.js b/test/store/index.js index 29d233495c..d9c806a486 100644 --- a/test/store/index.js +++ b/test/store/index.js @@ -428,6 +428,39 @@ describe('store', () => { a.set(false); assert.equal(b_started, false); }); + + it('works with undefined stores #1', () => { + const a = derived(null, (n) => { + return n; + }); + const values = []; + const unsubscribe = a.subscribe((value) => values.push(value)); + unsubscribe(); + assert.deepEqual(values, [undefined]); + }); + + it('works with undefined stores #2', () => { + const a = writable(1); + const b = derived([a, null, undefined], ([n, un1, un2]) => { + assert.equal(un1, undefined); + assert.equal(un2, undefined); + return n * 2; + }); + + const values = []; + + const unsubscribe = b.subscribe(value => { + values.push(value); + }); + + a.set(2); + assert.deepEqual(values, [2, 4]); + + unsubscribe(); + + a.set(3); + assert.deepEqual(values, [2, 4]); + }); }); describe('get', () => {