AsyncData not being called in nuxt

1.2k views Asked by At

I want to set category data at asyncData() hook. But MainHeader Page Component never calls asyncData even if it is placed in a page. Can you explain why MainHeader Page Component does not call asyncData?

MainHeader is placed inside "com" folder which is placed on pages (/pages/com/MainHeader)

<template>
  <div>
    <header-nav :cateList="cateList"/>
  </div>
</template>

<script>
import HeaderNav from '~/components/com/nav/HeaderNav.vue';
import CateApi from "~/util/api/category/cate-api";

export default {
  components: {HeaderNav},

  async asyncData(){
    const cateList = await CateApi.getDispCateList();
    return{
      cateList,
    }
  },

  data() {
    return {
      cateList: [],
    }
  },
}
</script>

default (/layouts/default)

<template>
<div>
  <main-header/>
  <Nuxt/>
</div>
</template>

<script>
import MainHeader from "~/pages/com/MainHeader.vue"
export default {
  components :{
    MainHeader,
  },
  name: "defaultLayout"
}
</script>
1

There are 1 answers

0
kissu On BEST ANSWER

You're probably reaching your page directly, something like /com/test-page I guess, there you will get first initial result on the server (you can check, you'll be getting a console.log in there), which is legit because this is how Nuxt works (server-side first then client-side).

Please follow the convention of naming your pages like my-cool-page and not myCoolPage and also keep in mind that asyncData works only inside of pages.

Your project is working perfectly fine, as an example, create the following file /pages/com/main-header.vue

<template>
  <div>
    <p> main header page</p>
    <header-nav :cate-list="cateList" />
  </div>
</template>

<script>
import HeaderNav from '~/components/com/nav/HeaderNav.vue';

export default {
  components: { HeaderNav },

  async asyncData() {
    console.log("check your server if accessing this page directly, otherwise you'll see this one in your browser if client-side navigation")
    const response = await fetch('https://jsonplaceholder.typicode.com/todos')
    const cateList = await response.json()

    return { cateList }
  },
}
</script>