What are the solutions to resolving issues with substrings in vue.js 3?

Recently starting out in vuejs, I am currently attempting to retrieve posts from a JSON file using the composition API. However, I have encountered a problem where too much text is being displayed after fetching the post data. This is not the desired outcome and I have been trying to address this issue using a specific 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>

In implementing this code snippet, an error message emerges stating:

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

Currently, I am unsure of how to resolve this issue. Can anyone provide assistance on this matter?

Answer №1

To address the undefined error, we can implement a check on the properties value.

const excerpt = computed(() => {
    let content = ''
    if (props.article && props.article.content){
      content = props.article.content.substring(0,100) + '...'
    }
    return content
}) 

Answer №2

props.post.body appears to be null. It would be helpful to investigate why it is returning null. However, if handling the null value is not critical, you can implement the ES10 feature known as the optional chaining operator like so:

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

Answer №3

Retrieve the first 100 characters of props.post.body and add an ellipsis at the end.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Storing a byte array in a local file using JavaScript: A Step-by-Step Guide

Recently, I encountered an issue while working with an openssl certificate. Specifically, when I tried to download the certificate from my API, it returned byte arrays that I needed to convert to a PEM file in order to access them through another API. The ...

How to divide a string by space after a specific character count using Javascript

I've been working on a tool that can divide input text into chunks based on a specific character count without breaking words in the process. Currently, I have set it to split the text after 155 characters. Even after conducting extensive research, ...

Display data side by side instead of stacking on top of each other in vue.js

I'm currently in the process of displaying data from my API using vue.js. I want to showcase information from various robots, with each robot's ID displayed at the top followed by its corresponding data. However, I'm encountering an issue wh ...

Apply the active class to the offspring element

I am just starting to learn Vue.js with bootstrap-vue and I'm looking to implement tabs on my page similar to the example here. <b-nav class="nav-tabs"> <b-nav-item v-bind:active=true v-bind:class="{ active : tab === 1 }" v-on:click="tab ...

Limit the number of rows per page when printing by utilizing JavaScript

In my PHP MySQL database, I have a table that displays all the data as shown in this https://i.sstatic.net/uM5tt.png image. I added a print button to put all the data into a hidden div and styled it as display none. When I click on the print button, the ...

Unable to deactivate button with jQuery in Django

Having some trouble with a simple jQuery function that should disable a Button if the selected dropdown value is blank. Can't figure out why it's not working. Here's the snippet of HTML code: <form action="{% url 'select_controller ...

Direction of Agm: Display the panel within a separate component

I have a unique setup where I have divided my page into two components, with one taking up 70% of the space and the other occupying 30%. The first component contains a map while the second one is meant to display information on how to reach a destination ( ...

Error encountered in React JS: Anticipated input was "CALC", "dimension", "number", but received unexpected end of input. CompileError originates from undefined CSS selector

After completing my entire project, I encountered an error while running yarn build. The error message from Yarn is as follows: Parse error on line 1: ^ Expecting "CALC", "LPAREN", "ADD", "SUB", "FUNCTION" ...

Explore a collection of dictionaries in Python

I am seeking a way to extract the names and types of fields from a Python dictionary list. The structure of my list is as follows: { "type" : "record", "name" : "warranty", "doc" : "Schema generated by Kite", "fields" : [ { "name" : "id", ...

After the element has been inserted, dom.byId will give you an undefined response

I have encountered an issue with a function that adds a div as a child to a dijit/layout/contentpane. The problem arises when I attempt to reference this div using dom.byId after adding it to the content pane. The function is triggered by a click event on ...

What might be the reason for my react-bootstrap modal not applying any styling?

I have two projects, one created by following a tutorial series and the other created independently later on, aiming to replicate the first project. I have narrowed down my issue to a basic comparison of index.js in both projects. This code is an edited v ...

Guide to integrating an element-ui component within a vuetify component

I recently started working with Vue.js and incorporated two libraries into my project: Element-UI and Vuetify. I added an Element-UI component called la-table to my template, which consists mostly of Vuetify components. However, after integrating this co ...

Express and 'websocket' packages are utilized in creating a WebRTC signaling server

I have been experimenting with code from the book "Getting Started with WebRTC" by Rob Manson. The original code, which is implemented using Node.js, sets up a real-time video call between two tabs in a web browser. I wanted to make a modification to use E ...

Angular Bootstrap notifications will stay open indefinitely and will not automatically dismiss after a certain period

I need help with adding alerts using Angular Bootstrap that should dismiss themselves after a certain timeout. However, the alerts are not dismissing on their own. Here's the code snippet: angular.module('ui.services').service('AlertSe ...

Engage with a feature that is currently displayed in a separate window

I'm working on a project that requires me to display 2 different components in separate browser windows. I've tried opening two windows and displaying the components, but now I'm wondering if there's a way for a component in one window ...

Utilizing JavaScript to Retrieve Selected Parameter in SSRS Report

Currently, I am incorporating an SSRS report into my website using Iframe. I aim to share a link to the specific filtered report, which is why I require knowledge of the report's parameters. My query pertains to how I can identify these parameters (e ...

What issues are plaguing my weak AJAX file upload feature?

Although AJAX File Upload may not be possible, I've chosen to use it as a placeholder name. :) My implementation involves utilizing this jQuery plugin. The main issue seems to arise from using it in a slightly different manner. Here's how I&apos ...

Can System.import in webpack be configured to utilize ajax for progress events?

Recently upgraded to webpack 2, and I've successfully set it up to automatically generate chunks based on System.import calls. It's pretty cool! However, I'm currently loading the initial chunk through an ajax call in order to monitor progr ...

I'm looking for a creative JavaScript prototype example that can help illustrate the concept of prototypes. Can someone share an interesting sample with me

I've been trying to wrap my head around prototypes, but I just can't seem to grasp their purpose and function. Is there anyone who can provide a straightforward example (such as a collegeStudent object) that will clarify the fundamentals of proto ...

The component is not displaying correctly

I am new to using React Context and Hooks in my project. I'm currently encountering an issue where the items in my component do not display on the screen when it initially loads, but they do appear when I click on a button. I have done some debugging ...