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

What is the destination for next() in Express js?

I'm new to javascript, nodejs, and express, and facing confusion with the usage of next(). I am trying to make my code progress to the next router using next(), but it seems to be moving to the next then instead. This is what my code looks like: // ...

A tutorial on dynamically adding fields with a dropdown list (populated from a database) and a text box using PHP and JQuery

I have multiple form components that I need to add dynamically, allowing users to add more than one. Firstly, there is a dropdown list with values populated from MySQL, followed by a text box for inquiries entry. The dropdown list displays a list of users, ...

What is preventing me from extracting the callback function from the app.get method in Node.js and Express?

In my server.js file, I'm attempting to do the following: // This code is not functioning as expected, and I am unsure why. var findBooks = function (err, books) { if (!err) { return response.send(books); } else { console.log( ...

Combining Option Value and Name Selection Using React Hooks

Currently, I am facing a situation where I need to retrieve two different values (item.id and item.name) to set the State when selecting an item from my dropdown menu. Right now, I am only able to do this for one value (item.id). Is it possible to achieve ...

Implementing experimental decorators and type reconciliation in TypeScript - A step-by-step guide

My basic component includes the following code snippet: import * as React from 'react'; import { withRouter, RouteComponentProps } from 'react-router-dom'; export interface Props { }; @withRouter export default class Movies extends R ...

Why is the output showing as abnormal?

There are occasions when I am unable to successfully execute this script! var b = [9,8,7,6,5,4,3,2,1]; var a = (function(){ var W = []; for(var k in b){ W[W.length] = { index : k, fx : function(){ console.log(k); ...

Vue3 compilation error: Every single file component must include at least one <template> or <script> block

Attempting to update a large existing codebase from Vue2 to Vue3 with the help of Webpack. I have successfully upgraded the necessary packages in package.json, which now looks like this (no issues encountered): "vue": "^3.2.45", "@vue/compat": "^3.2.45", " ...

Extract the content of a textbox within an iframe located in the parent window

Is it possible to retrieve the value of a text box in an iframe from the parent page upon clicking a button? Below is an example code snippet showcasing the situation: <div> <iframe src="test.html" > <input type=text id="parent_text"> & ...

Progress bar for AJAX file loading for Flash player

Looking to create a progress bar using AJAX for a flash file. Check out this demo here: I tried to analyze their page, but the JavaScript is encrypted and I'm not very skilled in JS. Any suggestions? Thank you! ...

What could be causing my JavaScript source to fail to load in an HTML document?

Currently, I am in the process of creating a basic offline dinosaur game using HTML, JS, and CSS that is well-known to everyone. I have been diligently working on it and have successfully made everything function for a few hours. However, out of nowhere, m ...

What is the process of saving a model with @tensorflow/tfjs-node version 2?

I've been struggling with setting up the save handler to save my model. I've scoured through various platforms like stack overflow and GitHub, but haven't had any luck. Help! Any guidance would be greatly appreciated!!! :) Below is a snipp ...

implement a jQuery loop to dynamically apply css styles

Attempting to utilize a jQuery loop to set a variable that will vary in each iteration through the loop. The plan is for this variable to be assigned to a css property. However, the issue arises where every css property containing the variable ends up with ...

What is the best way to showcase the information of each object on a click event in Vue.js?

My goal with this code is to display each day's class schedule when it is clicked on. However, the issue I'm facing is that the entire week's schedule is being displayed instead of just the selected day. What adjustments should I make in ord ...

How can you utilize jQuery to iterate through nested JSON and retrieve a specific matching index?

In the scenario where I have a nested JSON object like this: var library = { "Gold Rush": { "slides": ["Slide 1 Text","Slide 2 Text","Slide 3 Text","Slide 4 Text"], "bgs":["<img src='1.jpg' />","","<img src='2.j ...

HTTP request form

I'm currently working on a form that utilizes XMLHttpRequest, and I've encountered an issue: Upon form submission, if the response is 0 (string), the message displayed in the #output section is "Something went wrong..." (which is correct); Howe ...

Upgrade the arrow accordion in bootstrap by incorporating images instead

I have implemented a Bootstrap accordion with a toggle arrow. Here is an example: http://jsfiddle.net/zessx/r6eaw/12/ My question is, if I want to change the arrow with an image, what do I need to edit? Or how can I implement it? This is the image I want ...

Utilizing AJAX and PHP for seamless communication, retrieve and authenticate HTTPS SSL CERTIFICATE when interacting

Recently, I successfully created a node.js REST server located at . To develop the front-end, I am utilizing a combination of html, javascript, and php. However, when I attempted to implement an SSL certificate on the front-end, a problem arose: An issue ...

Determining if the device is connected to the internet

Is there a way to create a unique code using HTML, JavaScript, or jQuery that executes a random action when the website detects that the device is offline? ...

What does React default to for the implementation of the ``shouldComponentUpdate`` lifecycle method in its components?

Having a personalized approach to the shouldComponentUpdate() method as part of the React component lifecycle is not obligatory. I am aware that it serves as a boolean function determining whether the render() function will be triggered by changes in comp ...