Skip to content

Commit

Permalink
fix(api): execute query inside onMounted to avoid SSR hydration issues (
Browse files Browse the repository at this point in the history
  • Loading branch information
brc-dd committed Feb 5, 2024
1 parent 494672b commit db3cc44
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 3 deletions.
5 changes: 3 additions & 2 deletions lib/composables/Api.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { type Ref, ref } from 'vue'
import { Http } from '../http/Http'
import { tryOnMounted } from './Utils'

export interface Query<Data = any> {
loading: Ref<boolean>
Expand Down Expand Up @@ -30,8 +31,8 @@ export function useQuery<Data = any>(
const loading = ref(false)
const data = ref<Data | undefined>()

if (options.immediate !== false && !import.meta.env.SSR) {
execute()
if (options.immediate !== false) {
tryOnMounted(execute)
}

async function execute(): Promise<Data> {
Expand Down
10 changes: 9 additions & 1 deletion lib/composables/Utils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { type ComputedRef, type MaybeRefOrGetter, computed, toValue, useSlots } from 'vue'
import { type ComputedRef, type MaybeRefOrGetter, computed, getCurrentInstance, onMounted, toValue, useSlots } from 'vue'
import { isArray, isString } from '../support/Utils'

export type WhenCondition<T> = MaybeRefOrGetter<T>
Expand Down Expand Up @@ -61,3 +61,11 @@ export function useSlotValue(name = 'default'): ComputedRef<string | null> {
return v !== '' ? v : null
})
}

export function tryOnMounted(fn: () => void): void {
if (getCurrentInstance()) {
onMounted(fn)
} else if (!import.meta.env.SSR) {
fn()
}
}

0 comments on commit db3cc44

Please sign in to comment.