feat(useQuery): onResult & onError

This commit is contained in:
Guillaume Chau
2019-12-01 02:35:37 +01:00
parent 786dc5bc25
commit fac6fea2e6
2 changed files with 36 additions and 1 deletions
@@ -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
@@ -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,
}
}
@@ -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,
}
}