Skip to content

Commit

Permalink
fix: missing updates for reconnecting stores
Browse files Browse the repository at this point in the history
  • Loading branch information
schummar committed Feb 27, 2024
1 parent b10f346 commit 9e6246c
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 9 deletions.
16 changes: 8 additions & 8 deletions src/lib/calculatedValue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,14 +78,16 @@ export function calculatedValue<T>(store: Store<T>, notify: () => void): Calcula

async function connect(createConnection: Connection<T>) {
if (!active) {
connection = { active: false };
return;
}

const actions: AsyncConnectionActions<any> = {
set(value) {
set(_value) {
connection?.active &&
q(() => {
store.set(value);
value = _value;
notify();
});
},
updateValue(update) {
Expand Down Expand Up @@ -147,6 +149,8 @@ export function calculatedValue<T>(store: Store<T>, notify: () => void): Calcula

if (value instanceof Promise) {
value.finally(() => whenExecuted.resolve()).catch(() => undefined);
} else {
whenExecuted.resolve();
}

function check() {
Expand All @@ -164,17 +168,13 @@ export function calculatedValue<T>(store: Store<T>, notify: () => void): Calcula

function stop() {
cancelEffect();
whenExecuted.resolve();
whenConnected.resolve();

if (connection) {
connection.active = false;
connection.cancel?.();
q.clear();

whenConnected.reject();
whenExecuted.reject();
} else {
whenConnected.resolve();
whenExecuted.resolve();
}
}

Expand Down
21 changes: 20 additions & 1 deletion test/core/store.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { createStore } from '../../src';
import { createStore, set } from '../../src';
import { defaultEqual, shallowEqual } from '../../src/lib/equals';
import { flushPromises } from '../testHelpers';

beforeEach(() => {
vi.useFakeTimers();
Expand Down Expand Up @@ -331,4 +332,22 @@ describe('static store', () => {
expect(reaction1).toHaveBeenCalledTimes(2);
expect(reaction2).toHaveBeenCalledTimes(2);
});

test('connect', async () => {
const state = createStore(({ connect }) => {
connect(({ set }) => {
set(2);
return () => undefined;
});

return 1;
});

expect(state.get()).toBe(1);

state.subscribe(() => undefined);
await flushPromises();

expect(state.get()).toBe(2);
});
});

0 comments on commit 9e6246c

Please sign in to comment.