The Vue.JS application encountered an error while making an API request, resulting in an uncaught TypeError: Cannot read properties of undefined related to the 'quote'

<template>

    <article class="message is-warning">
        <div class="message-header">
            <span>Code Examples</span>
        </div>
        <div class="message-body">
                <span v-html="fetchedExamples.data.example"></span>
                <span>{{fetchedExamples.data.author}}</span> 
        </div>
    </article>

</template>

<script>
    export default {
        data(){
            return {
               
                fetchedExamples: [],
                contentUrl: "https://apiurl.tld/"
            };
        },
        mounted() {
            this.getExamples(this.contentUrl, "examples");
            
        },
        methods: {
            async getExamples(url, collection) {
                try {
                    
                    let response = await fetch(url + collection+"/"+Math.ceil(Math.random()*6));
                    this.fetchedExamples = await response.json();
                } catch (error) {
                    console.log(error);
                }
            }
        }
    };
</script>

I am attempting to randomly retrieve examples from a specific project's API. However, whenever I run this code, I encounter the following error :

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'quote').

I have tested multiple solutions without success, and now I'm seeking assistance in identifying what might be causing this code to malfunction.

Your help would be greatly appreciated.

Answer №1

One issue lies in attempting to access fetchedQuotes.data.quote before it has been fetched. To address this, ensure that your fetchedQuotes is not empty within the html tag.

<span v-html="fetchedQuotes.data.quote" v-if="fetchedQuotes.length != 0"></span>

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

Is it possible for jQuery to create a popup window displaying a specific value?

Using JavaScript, I have implemented functionality to open a child window when the user clicks on a button from the parent window. The child window contains a textbox and a button. When the user clicks on the button in the child window, I want to retrieve ...

Searching for specific objects within a nested array in TypeScript

I have been searching for examples for a while now, but I haven't found anything similar. My understanding of the filter function is lacking, so any assistance would be greatly appreciated. The goal is to remove elements from the object where the nest ...

Is there a way to eliminate the mongoose event listener registered onConnect in the Socket.io Leak issue?

Whenever a user connects via socket.io, the following subscribe event is triggered: socket.on('subscribe', function(room) { console.log('joining room', room.id); socket.join(room.id); socket.roomName = room.id; // ...

What is the process for integrating a tensorflow.js model into a React-based web application?

I've been working on a React web application in Typescript that involves loading a tensorflow.js model and then applying it each time the component updates. While I successfully implemented this in a small demo app without React, I am facing some chal ...

Guide on creating a 4-point perspective transform with HTML5 canvas and three.js

First off, here's a visual representation of my objective: https://i.stack.imgur.com/5Uo1h.png (Credit for the photo: ) The concise question How can I use HTML5 video & canvas to execute a 4-point perspective transform in order to display only ...

Steps for wrapping a class with a higher order component

Is it feasible to encapsulate a class component within a higher order component (HOC) that is also a class? import React, { Component } from "react"; import { View } from "react-native"; import { Toast } from "react-native-easy-toast"; const withToast = ...

Make sure to wait for the fetch response before proceeding with the for loop in JavaScript using Node.js

I am facing an issue with my function that connects to a SOAP web service. The problem arises from the fact that the web service has limited connections available. When I use a for or foreach loop to search through an array of items in the web service, aro ...

Sending data from the server to the client in MVC using C#

I sent a token from a View to a function in my HomeController, and now I need to process the token and send back the information to the frontend. I assumed that the resultData returned by the ajax call would be the output of GetMyData, but it turns out it& ...

Encapsulating data with JSON.stringify

I'm currently working on creating an object that has the following structure: let outputOut = { "_id": id[i], "regNum": code[i], "sd": sd[i], "pd": ptOut, "p": p[i], ...} //output fs.writeFile('./output/file.json', JSON ...

Error: The VueComponent.onResize function encountered an uncaught TypeError because it cannot read the property 'offsetHeight' of an undefined variable

<div ref="controls" class="varie controls"> <div class="control" v-if="spin!='"> <span>Saved datee</span><span>{{ }}</span> </div> <button v-on:click="apply()">Aopply</button> </div& ...

Requesting data asynchronously using AJAX and displaying the filtered results on a webpage using JSON

When I send a request to my node.js server for a .json file containing person information (first name, last name), I want the data to be filtered based on user input. For example: When I request the .json file from the server, it gives me a list of people ...

What is the best way to use jQuery to listen for a container resizing event?

I am confident that I can achieve this: $(window).resize(function() {funkyfunc();}); The above code will execute funkyfunc() whenever the window is resized. However, my issue lies in wanting to resize one control after another has been resized. I've ...

Getting the specific nested array of objects element using filter in Angular - demystified!

I've been attempting to filter the nested array of objects and showcase the details when the min_age_limit===18. The JSON data is as follows: "centers": [ { "center_id": 603425, "name" ...

contrasts in regex special characters: .net versus javascript

Here is my current javascript implementation: EscapeForRegex = function(input) { var specials = ["[", "\\", "^", "$", ".", "|", "?", "*", "+", "(", ")", "{", "}"] for (var k in specials) { var special = specials[k]; ...

Issue with importing and exporting external types causing failures in Jest unit tests for Vue 2

I am in the process of creating a package that will contain various types, enums, consts, and interfaces that I frequently use across different projects. To achieve this, I have set up a main.ts file where I have consolidated all the exports and specified ...

Finding the difference or sum within an array to identify the two numbers that produce a new array

In order to clarify, I am looking for a method to identify the two smallest numbers in a sorted array that will result in a specific number when subtracted. The process can be broken down into the following steps: Iterate through the array and designate ...

The element 'Component' cannot be utilized as a JSX component since its type 'ReactElement<any, any> | Component<{}, any, any>' is not a valid JSX element

I'm currently facing an issue while running "yarn build" and/or "npm run build" on a repository. The error persists for both commands. My goal is to build and deploy this code to an AWS environment, but I am stuck at resolving the errors that indicate ...

Header Stability TransitionAndView

I'm not very experienced with JavaScript, so please bear with me. I'm attempting to create a fixed header that transitions to 50% opacity when scrolled down and returns to full opacity (opacity: 1.0) when scrolled back to the top. Here is my cur ...

There seems to be an issue with the Webpack command as it is unable to locate the module 'webpack'

Currently, I am in the process of developing a web application using Vue.js for the frontend. To work with Vue.js, webpack is required and has been installed globally on my system. However, whenever I attempt to execute the 'webpack' command, an ...

NativeScript element isn't showing up

Being relatively new to application development with NativeScript, I find myself in a situation where I need assistance in finding a solution. Drawing from my experience with PHP, I am now looking to create a template for each "page" of the application. Th ...