Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: load icons on mount rather than within setup #82

Merged
merged 1 commit into from
Oct 3, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 24 additions & 13 deletions src/runtime/components/elements/Icon.vue
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,9 @@

<script setup lang="ts">
import type { IconifyIcon } from '@iconify/vue'
import { computed, ref, watch } from 'vue'
import { Icon as Iconify } from '@iconify/vue/dist/offline'
import { loadIcon } from '@iconify/vue'
import { useNuxtApp, useState } from '#imports'
import { useNuxtApp, useState, computed, watch, onMounted } from '#imports'

const props = defineProps({
name: {
Expand All @@ -20,19 +19,31 @@ const props = defineProps({
})
const nuxtApp = useNuxtApp()
const state = useState('u-icons', () => ({}))
const isFetching = ref(false)
const icon = computed<IconifyIcon | null>(() => state.value?.[props.name])

const isFetching = computed(() => !!state.value?.[props.name]?.then)
const icon = computed<IconifyIcon | null>(() => !state.value?.[props.name] || state.value[props.name].then ? null : state.value[props.name])
const component = computed(() => nuxtApp.vueApp.component(props.name))
const loadIconComponent = async () => {
if (component.value) { return }
if (!state.value?.[props.name]) {
isFetching.value = true
state.value[props.name] = await loadIcon(props.name).catch(() => null)
isFetching.value = false
}

const loadIconComponent = (name: string) => {
state.value = state.value || {}
if (nuxtApp.vueApp.component(props.name) || state.value[name] || state.value[name] === null) { return }

state.value[name] = loadIcon(name)
.then((res) => { state.value[name] = res })
// We won't try to load this icon again if it fails
.catch(() => { state.value[name] = null })

// return an awaitable promise
return state.value[name]
}

onMounted(() => {
watch(() => props.name, loadIconComponent, { immediate: true })
})

if (process.server) {
await loadIconComponent(props.name)
}
watch(() => props.name, loadIconComponent)
!component.value && (await loadIconComponent())
</script>

<script lang="ts">
Expand Down