Search code examples
javascriptvue.jsfetchnuxt.js

Unable to use $fetchState in Nuxt 2.12


So I'm trying to use the new functionality describe in the documentation.

However I'm ending up getting this error :

Property or method "$fetchState" is not defined on the instance but referenced during render.

Even though my component define clearly the fetch() method and I manage to get something out of it.

<template>
    <div v-if="$fetchState">
        <p v-if="$fetchState.pending">Fetching posts...</p>
        <p v-else-if="$fetchState.error">Error while fetching posts</p>
        <div v-else>
            <div v-if="content.content1" v-html="content.content1" />
            <div v-if="content.content2" v-html="content.content2" />
        </div>
    </div>
</template>
<script>
import { mapState } from 'vuex'

export default {
    async fetch({ store, error }) {
        try {
            await store.dispatch('home/fetchContent')
        } catch (e) {
            error({
                statusCode: 503,
                message: 'Unable to fetch'
            })
        }
    },
    computed: mapState({
        content: (state) => state.home.content
    })
}
</script>

Has anybody ever encountered that before ?


Solution

  • When you are using fetch(context) you use old fetch, you should get context from this, if you need to.

      async fetch() {
        const { store, error } = this.$nuxt.context
    
        try {
          await store.dispatch('home/fetchContent')
        } catch (e) {
          error({
            statusCode: 503,
            message: 'Unable to fetch'
          })
        }
      },
    

    https://nuxtjs.org/blog/understanding-how-fetch-works-in-nuxt-2-12/#fetch-before-nuxt-2-12