Skip to content

Commit

Permalink
feat(useQuery): onResult & onError
Browse files Browse the repository at this point in the history
  • Loading branch information
Guillaume Chau committed Dec 1, 2019
1 parent 786dc5b commit fac6fea
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
8 changes: 7 additions & 1 deletion packages/vue-apollo-composable/src/useQuery.ts
Expand Up @@ -42,7 +42,9 @@ export function useQuery<
* Result from the query
*/
const result = ref<TResult>()
const error = ref(null)
const resultEvent = useEventHook<ApolloQueryResult<TResult>>()
const error = ref<Error>(null)
const errorEvent = useEventHook<Error>()

// Loading

Expand Down Expand Up @@ -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)[] = []
Expand Down Expand Up @@ -260,5 +264,7 @@ export function useQuery<
query,
refetch,
subscribeToMore,
onResult: resultEvent.on,
onError: errorEvent.on,
}
}
29 changes: 29 additions & 0 deletions packages/vue-apollo-composable/src/util/useEventHook.ts
@@ -0,0 +1,29 @@
export function useEventHook<TParam = any> () {
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,
}
}

0 comments on commit fac6fea

Please sign in to comment.