Composition-api: fix: Unable to start loader manually.

Created on 28 Jan 2021  路  2Comments  路  Source: nuxt-community/composition-api

馃悰 The bug
Thanks for developing the nuxtjs/composition-api!
I usually use it too.
However, I recently encountered a bug.

What I want to achieve

I want to use this feature of Nuxt( https://nuxtjs.org/docs/2.x/features/loading#programmatically-starting-the-loading-bar ) to display the loader manually, but I get an error when I write the following in the setup function.

my loader component is like this

// ~/components/MyLoader.vue
<template>
  <div>
       <div v-if="isLoading" class="circle-loader" />
  </div>
</template>

<script lang="ts">
  export defalut defineComponent({
    ...,
    setup(_, { root }) {
        const isLoading = ref(false)
        const start = () => (isLoading.value = true)
        const finish = () => (isLoading.value = false)
        return { isLoading, start, finish }
    }
  })
</script>

and I registered it in nuxt.config.ts.

// nuxt.config.ts
export default {
    ...,
    loading: '~/components/MyLoader.vue'
}

and in pages

<template>
    ...
</template>

<script lang="ts">
  export default defineComponent({
    setup(_, { root }) {
        const post = ref()
        useFetch(async () => {
            root.$nuxt.$loading.start()
            post.value = await getPost()
            root.$nuxt.$loading.finish()
        })
    }
  })
<s/cript>

error

However, this code catches the error in the fetch.

// $fetchState
{  error: { message: "root.$nuxt.$loading.start is not a function", statusCode: 500 }}

I don't understand it, but when I assign a function to a button and execute it, it works.

// it work
<button @click="showLoader" />
...
setup(_, { root }) {
  const showLoader = () => {
      root.$nuxt.$loading.start()
  }
  return { showLoader }
}

The loader is running during page transitions, but not in the part that uses root.$nuxt.$loading.start().

Is this a bug? Or am I writing it wrong?
I want to display the component registered as a loader during fetch.

version

nuxt: 2.14.6
@nuxtjs/composition-api: 0.14.0
bug

Most helpful comment

@HajifuDev $loading is only injected after mounting the component - so it is not present on server side, which I would imagine is when you are getting the error. Check that $loading exists and has the properties you expect before interacting with it.

All 2 comments

@HajifuDev $loading is only injected after mounting the component - so it is not present on server side, which I would imagine is when you are getting the error. Check that $loading exists and has the properties you expect before interacting with it.

@danielroe Thanks for the reply.
I too realized my mistake. Thanks for addressing it!

Was this page helpful?
0 / 5 - 0 ratings