useFetch in onMounted not fetching data on direct link open nuxt3

Viewed 994

I'm using the useFetch to fetch the data in the composition api and then calling the function in onMounted hook in components, here is the code.

useShows.ts (composable)

export function useShows(){

    var shows = useState<Show[]>('shows')

    const fetchShows = async() => {
        const {data, pending} = await useFetch<Show[]>('http://localhost:3000/shows')
        shows.value = data.value
    }

    return {shows, fetchShows}
}

shows.vue

<script setup lang="ts">

    var { shows, fetchShows } = useShows()

    onMounted(() => {
        console.log("On mounted called")
        fetchShows()
    })
</script>

<template>
    <div>{{shows}}</div>
</template>

When I'm navigating to /shows from the home page it is working fine, but when I direct open the link localhost/shows it is not working and only giving me the null.

1 Answers

I have the exact same problem. I solved it by wrapping it within a nextTick.

await nextTick(async () => {
  await fetchShows()
})
Related