Composition-api: fix: error() in setup() with useAsync() should work as in asyncData

Created on 12 Mar 2021  ·  3Comments  ·  Source: nuxt-community/composition-api

🐛 The bug
When the error() method from useContext() is called in setup() it resolves to failed hydration. It returns the index page first and after client-side code is loaded it shows an error page, which causes hydration errors.

🛠️ To reproduce
Steps to reproduce the behavior:

  1. Create index.vue in pages folder and add code
import { defineComponent, useContext, useAsync, useRoute } from '@nuxtjs/composition-api'

export default defineComponent({
    name: 'Index',
    setup () {
        const { error } = useContext()
        const route = useRoute()

        useAsync(() => {
            error({ statusCode: 404 })
        }, route.value.fullPath)

        return {}
    }
})

🌈 Expected behavior
I would expect it to work similarly to asyncData() which returns an error page

bug

All 3 comments

@bernessco Unfortunately, useAsync won't behave the same way as asyncData as it's called in serverPrefetch. asyncData is actually called entirely outside the normal Vue component lifecycle so it is able to redirect to an error page (unlike fetch() or any of the Composition API methods provided here). You'll need to handle the error yourself within the component (for example, by setting an ssrRef to 'error' and then redirecting or taking some other action on client-side - such as in onBeforeMount).

@danielroe Thanks for your response! I had the same hydration errors when using error({ statusCode: 404 }) in setup without useAsync is it expected behaviour?

@danielroe I have the same problem as @bernessco. This is how I reproduce:

<script lang="ts">
export default defineComponent({
  name: 'Index',
  setup () {
    const { error } = useContext()
    error({ statusCode: 404 })
  },
})
</script>

It seems like that server render the Index page first instead of the error page. I wonder if it's even possible to call useContext().error in setup function.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

MartinMalinda picture MartinMalinda  ·  7Comments

theartkod picture theartkod  ·  3Comments

Quineone picture Quineone  ·  5Comments

namadnuno picture namadnuno  ·  4Comments

tcastelly picture tcastelly  ·  7Comments