From c0724b91d917e4ba851bb133dce95db07fad0f19 Mon Sep 17 00:00:00 2001 From: Tai Sakuma Date: Mon, 18 Sep 2023 15:11:36 -0400 Subject: [PATCH] extract useState() --- src/utils/query-state.ts | 44 ++++++++++++++++++++++++++++++---------- 1 file changed, 33 insertions(+), 11 deletions(-) diff --git a/src/utils/query-state.ts b/src/utils/query-state.ts index 93170c2..1858de2 100644 --- a/src/utils/query-state.ts +++ b/src/utils/query-state.ts @@ -1,4 +1,5 @@ import { ref, computed, watch } from "vue"; +import type { Ref } from "vue"; import { useStore } from "@/plugins/pinia/stores/main"; import type { UseQueryResponse, AnyVariables } from "@urql/vue"; import { refThrottled } from "@vueuse/core"; @@ -33,16 +34,6 @@ export function useQueryState( error.value = val === State.Error ? "Error from Dev Tools" : null; }); - const state = computed(() => { - if (devtoolState.value !== State.Off) return devtoolState.value; - if (refreshing.value) return State.Loading; - if (query.fetching.value) return State.Loading; - if (error.value) return State.Error; - if (isEmpty?.(query)) return State.Empty; - if (isNull?.(query)) return State.None; - return State.Loaded; - }); - const store = useStore(); watch( () => store.nApolloMutations, @@ -53,6 +44,15 @@ export function useQueryState( const { refreshing, refreshError, refresh } = useRefresh(query); + const state = useState( + query, + devtoolState, + refreshing, + error, + isEmpty, + isNull + ); + watch(refreshError, (e) => { error.value = e; }); @@ -61,11 +61,33 @@ export function useQueryState( init, error, devtoolState, + refresh, + ...state, + }; +} + +function useState( + query: UseQueryResponse, + devtoolState: Ref, + refreshing: Ref, + error: Ref, + isEmpty: ((query: UseQueryResponse) => boolean) | undefined, + isNull: ((query: UseQueryResponse) => boolean) | undefined +) { + const state = computed(() => { + if (devtoolState.value !== State.Off) return devtoolState.value; + if (refreshing.value) return State.Loading; + if (query.fetching.value) return State.Loading; + if (error.value) return State.Error; + if (isEmpty?.(query)) return State.Empty; + if (isNull?.(query)) return State.None; + return State.Loaded; + }); + return { loading: computed(() => state.value === State.Loading), loaded: computed(() => state.value === State.Loaded), empty: computed(() => state.value === State.Empty), notFound: computed(() => state.value === State.None), - refresh, }; }