0

I'm new in vuejs, and I'm trying to fetch posts from a JSON file using the composition API, but I'm having a problem. After fetching post, too many texts are being displayed, which is what I don't want. I have tried to fix it using the following method:

<template>
    <div class="max-w-md bg-white rounded-xl shadow-md overflow-hidden md:max-w-2xl m-6" v-for="post in post" :key="post.id">
        <div class="md:flex">
            <div class="md:flex-shrink-0" >
            <img class="h-48 w-full object-cover md:h-full md:w-48" src="assets/store.jpg" alt="Man looking at item at a store">
            <div class="p-8">
            <div class="uppercase tracking-wide text-sm text-indigo-500 font-semibold">News</div>
            <router-link :to="{name: 'Details', params:{id: post.id}}"><strong>{{post.title}}</strong></router-link>
            <p class="mt-2 text-gray-500">{{snippet}}</p>
            </div>
        </div>
    </div>
</template>

<script>
import { computed } from 'vue'
export default {
    props:['post'],
    setup(props) {
        const snippet = computed(() => {
            return props.post.body.substring(0,100) + '...'
        }) 
        return{snippet}
    }
}
</script>

The problem here is that when I run this piece of code, I get an error that says:

TypeError: Cannot read properties of undefined (reading 'substring')

And I don't even know how to go about this at the moment. Could someone please help?

1
  • 1
    Looks like props.post.body is not defined. Please verify that props.post.body has a string value. Commented Sep 23, 2021 at 5:53

3 Answers 3

1

We can handle the undefined error by checking the properties value.

const snippet = computed(() => {
    let body = ''
    if (props.post && props.post.body){
      body = props.post.body.substring(0,100) + '...'
    }
    return body
}) 
Sign up to request clarification or add additional context in comments.

Comments

1

props.post.body is undefined. It's better to debug why it's undefined. Nevertheless, if the undefined can be ignored you can use the following ES10 optional chaining operator.

props.post.body?.substring(0,100)

Comments

0

return String(props.post.body).substring(0,100) + '...';

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.