Search code examples
nuxt.jsvuejs3apollonuxt3.js

How to properly use data and assign variables from queries with Nuxt Apollo and useAsyncQuery?


I am using Nuxt 3 with Nuxt Apollo. My queries work fine on page refresh / landing but give me an undefined error when navigating between pages.

I currently have something like this:

<template>
  <p>This is my page content: {{ page.entry.children }}</p>
</template>

<script setup>
import { myQuery as query } from '@/graphql/queries'

const variables = { limit: 5 }

const { data: page } = await useAsyncQuery(query, variables)
</script>

Apart trying to solve the route issue, I am also not understanding how to reassing the variable for a cleaner code. For example, instead of the above, to have:

<template>
  <p>This is my page content: {{ myPage }}</p>
</template>

After something like:

const myPage = page.entry.children

This, unfortunately, it's undefined. I also tried to declare const myPage = ref() then assing myPage.value = page.entry.children, but with same results.

I also feel that for the same issue I am not able to use the data on useSeoMeta, where even if I do:

useSeoMeta({
  title: () => page?.entry?.metaTitle
)}

it returns undefined (but works on the page)


Solution

  • Thanks to this topic I discovered of a hidden .value that needs to be added to the object. It doesn't show up when you print it out, hence the confusion.

    instead of:

    const myPage = page.entry.children
    

    it needs to be:

    const myPage = page.value.entry.children
    

    What is even more weird is that on the template it's the other way around (page.value.entry.children will not work).

    This also solved the useSeoMeta issue, but not the data refresh on route change, which I believe it's a separate issue.