skip to Main Content

I hate two pages in a Vue application. One is working great, the other is throwing up this error:

One page loads a collection of wordpress posts (Blog.vue), the other displays an individual post. Both are using the same approach, Blog.vue works fine, BlogPost.vue errors with:

TypeError: $setup.post is undefined

Blog.vue

<template>
<v-col v-for="post in wpposts" cols="12" sm="4">
</template>
<script lang="ts" setup>
  import ...

  onMounted(() => {
    getPosts();
  })

  onUpdated(() => {
    var msnry = new Masonry('.masonry', {
        // options
        itemSelector: "[class*='col-']",
    });
  })

  const rootUrl = 'https://myurl.com/';

  const wpposts = ref()

  async function getPosts() {
    const data = await fetchData(new Request(rootUrl + 'index.php/wp-json/wp/v2/posts?_embed')) as Post[];
    data.forEach(element => {
    ...
    wpposts.value = data;
}

const fetchData = async <T>(request: Request): Promise<T> => {
    const response = await fetch(request);
    return await response.json();   
}

BlogPost.vue
Errors with

TypeError: $setup.post is undefined
<template>

  <v-container fluid>
    <!-- <Suspense> -->
    
    <v-row>

        <v-col cols="12" sm="4">

          <v-img height="250" :src="post.imageUrl" cover></v-img> <!-- Blowsup -->

  </v-container>
  </template>
<script lang="ts" setup>
  import { ref, onMounted, onUpdated, type Ref, reactive } from 'vue'
  import { DateTime } from "luxon";
  import { Post } from "../blogtypes";

  const props = defineProps({
    id: String,
    url: String
  })

  onMounted(() => {
    getPost();
  })

  const post = ref()

  const rootUrl = 'https://myurl.com/';

   async function getPost() {
    const data = await fetchData(new Request(rootUrl + 'index.php/wp-json/wp/v2/posts/' + props.id + '?_embed')) as Post;
    ...
    post.value = data;
}

  const fetchData = async <T>(request: Request): Promise<T> => {
    const response = await fetch(request);
    return await response.json();   
}
</script>

I’m really not sure of the best way to address this error since I have one component working with this approach and one erroring with TypeError: $setup.post is undefined

2

Answers


  1. Chosen as BEST ANSWER

    I've actually just fixed thie code by declaring the ref like:

    const post = ref<Post | null>(null);
    

    And accessing it like:

    <v-img height="250" :src="post?.imageUrl" cover></v-img>
    

  2. It looks like the post ref is undefined at the first rendering which causes this issue try to use v-if or optional chaining :

       <v-img v-if="post" height="250" :src="post.imageUrl" cover></v-img>
    

    or

       <v-img height="250" :src="post?.imageUrl" cover></v-img>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search