From fac6fea2e6186f12de8d3ab889bebb2f3a01f8d7 Mon Sep 17 00:00:00 2001 From: Guillaume Chau Date: Sun, 1 Dec 2019 02:35:37 +0100 Subject: [PATCH] feat(useQuery): onResult & onError --- .../vue-apollo-composable/src/useQuery.ts | 8 ++++- .../src/util/useEventHook.ts | 29 +++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 packages/vue-apollo-composable/src/util/useEventHook.ts diff --git a/packages/vue-apollo-composable/src/useQuery.ts b/packages/vue-apollo-composable/src/useQuery.ts index 094b46a7..b755a459 100644 --- a/packages/vue-apollo-composable/src/useQuery.ts +++ b/packages/vue-apollo-composable/src/useQuery.ts @@ -42,7 +42,9 @@ export function useQuery< * Result from the query */ const result = ref() - const error = ref(null) + const resultEvent = useEventHook>() + const error = ref(null) + const errorEvent = useEventHook() // Loading @@ -92,12 +94,14 @@ export function useQuery< result.value = queryResult.data loading.value = queryResult.loading networkStatus.value = queryResult.networkStatus + resultEvent.trigger(queryResult) } function onError (queryError: any) { error.value = queryError loading.value = false networkStatus.value = 8 + errorEvent.trigger(queryError) } let onStopHandlers: (() => void)[] = [] @@ -260,5 +264,7 @@ export function useQuery< query, refetch, subscribeToMore, + onResult: resultEvent.on, + onError: errorEvent.on, } } diff --git a/packages/vue-apollo-composable/src/util/useEventHook.ts b/packages/vue-apollo-composable/src/util/useEventHook.ts new file mode 100644 index 00000000..6d8b3b3f --- /dev/null +++ b/packages/vue-apollo-composable/src/util/useEventHook.ts @@ -0,0 +1,29 @@ +export function useEventHook () { + const fns: ((param?: TParam) => void)[] = [] + + function on (fn: (param?: TParam) => void) { + fns.push(fn) + return { + off: () => off(fn), + } + } + + function off (fn: (param?: TParam) => void) { + const index = fns.indexOf(fn) + if (index !== -1) { + fns.splice(index, 1) + } + } + + function trigger (param?: TParam) { + for (const fn of fns) { + fn(param) + } + } + + return { + on, + off, + trigger, + } +} \ No newline at end of file