Skip to content

Commit 63ec4dd

Browse files
improve Vue reactivity internals.
1 parent e758aa6 commit 63ec4dd

File tree

1 file changed

+22
-6
lines changed

1 file changed

+22
-6
lines changed

packages/vue/src/composables/useWatchedQuerySubscription.ts

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
import { WatchedQuery } from '@powersync/common';
2-
import { reactive, UnwrapNestedRefs, watchEffect } from 'vue';
2+
import { Ref, ref, watchEffect } from 'vue';
3+
4+
type RefState<ResultType = unknown, Query extends WatchedQuery<ResultType> = WatchedQuery<ResultType>> = {
5+
[K in keyof Query['state']]: Ref<Query['state'][K]>;
6+
};
37

48
/**
59
* A composable to access and subscribe to the results of an existing {@link WatchedQuery} instance.
@@ -27,18 +31,30 @@ export const useWatchedQuerySubscription = <
2731
Query extends WatchedQuery<ResultType> = WatchedQuery<ResultType>
2832
>(
2933
query: Query
30-
): UnwrapNestedRefs<Query['state']> => {
31-
// Creates a reactive variable which will proxy the state
32-
const state = reactive({ ...query.state }) as UnwrapNestedRefs<Query['state']>;
34+
): RefState<ResultType, Query> => {
35+
// This uses individual refs in order for the destructured use of this hook's return value to
36+
// function correctly.
37+
const data = ref(query.state.data) as Ref<Query['state']['data']>;
38+
const error = ref(query.state.error);
39+
const isLoading = ref(query.state.isLoading);
40+
const isFetching = ref(query.state.isFetching);
3341

3442
watchEffect((onCleanup) => {
3543
const dispose = query.registerListener({
3644
onStateChange: (updatedState) => {
37-
Object.assign(state, updatedState);
45+
data.value = updatedState.data;
46+
error.value = updatedState.error;
47+
isFetching.value = updatedState.isFetching;
48+
isLoading.value = updatedState.isLoading;
3849
}
3950
});
4051
onCleanup(() => dispose());
4152
});
4253

43-
return state;
54+
return {
55+
data,
56+
error,
57+
isFetching,
58+
isLoading
59+
} as RefState<ResultType, Query>;
4460
};

0 commit comments

Comments
 (0)