Skip to content

Commit

Permalink
fix: load icons on mount rather than within setup (#82)
Browse files Browse the repository at this point in the history
  • Loading branch information
danielroe authored Oct 3, 2022
1 parent bf25ad1 commit 62361bf
Showing 1 changed file with 24 additions and 13 deletions.
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

1 comment on commit 62361bf

@vercel
Copy link

@vercel vercel bot commented on 62361bf Oct 3, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

ui – ./

ui-nuxtlabs.vercel.app
ui-git-dev-nuxtlabs.vercel.app
nuxthq-ui.vercel.app

Please sign in to comment.