[Vue alert]: Issue with rendering: "Sorry, unable to read property 'correct_answer' as it is undefined"

My code fetches data from an API. The questions display correctly, but the answers cause an error that crashes the app.

Initially, the code worked fine in App.vue, but moving it to a different view page caused the crash. Any suggestions on how to fix this?

<template>
    <div class="container-question" width=800px>
        <b-row>
            <b-col cols="8">
                <h1> Recently Asked </h1>
                <ul 
                    v-for="(question1,index) in questions" 
                    :key="index" 
                    :question1="questions[index]"
                >
                    <li>
                        {{ question1.question }}
                        <b-row id="asked-info">
                            <p>Asked by:  </p>
                            <div 
                                id="user" 
                                v-for="(answer, index) in answers"
                                :key="index"
                            > 
                                {{ answer }} 
                            </div>
                        </b-row>
                        <b-row>
                            <b-button class="outline-primary" style="margin:auto;">
                                Answer
                            </b-button>
                        </b-row>
                    </li>
                </ul>
            </b-col>
        </b-row>
    </div>
</template>

<script>
export default {
    data() {
        return {
            questions: [],
            index: 0,
    }
},

computed: {
    answers() {
        // The problem lies here: it can't read the correct_answer and throws an error
        let answers = [this.question1.correct_answer]; 
        return answers;
    },
},

mounted: function() {
    fetch('https://opentdb.com/api.php?amount=10&category=9&difficulty=medium&type=multiple', {
        method: 'get'
    })
      .then((response) => {
          return response.json()
      })
      .then((jsonData) => {
          this.questions = jsonData.results
      })
    }
}

Answer №1

question1 is a variable specific to the v-for loop in the template, it is not part of the this object.

It appears that the answers computed property may be redundant (as it simply places the correct answer in an array). Instead, you could use a method like the following:

methods: {
  answers(question1) {
    let answers = [question1.correct_answer]; 
    return answers;
  }
}
<div 
  id="user" 
  v-for="(answer, index) in answers(question1)"
  :key="index"
> 

Answer №2

Have you attempted utilizing an asynchronous function? Like in the example below

computed: {
        async getAnswers() {
          let answers = [this.question1.correct_answer];
          return await answers;
        },
       
      },

When paired with a v-if statement

  <div id="user" v-if="answer.id" v-for="(answer, index) in answers" :key="index"> 
 {{ answer }} 
  </div>
 

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 best way to eliminate the space underneath a graph?

Despite trying multiple solutions, I'm still struggling to remove the excess blue space below the graph that appears when clicking the submit button. Any insights into what might be causing this issue? JSFIDDLE Below are the CSS styles related to t ...

What is the best way to place two stacked buttons side by side in an inline format?

I am trying to rearrange the layout of a bootstrap modal that includes two multiple select elements and two buttons. My goal is to have all controls inline, with the buttons stacked on top of each other. Here's an example of what I'm aiming for: ...

Concealing items by placing them strategically between the camera and certain objects in Three.js

At the moment, my project involves utilizing three.js with several objects in the scene. One of the key features I am working on is the ability to select an object and have all other objects between the camera and the selected one hidden or removed. I am ...

troubleshooting problems with feathers.JS using the npm start command

After developing two separate feathersJS applications, I encountered a situation where running npm start resulted in two unique types of errors for each app. How can I go about resolving this issue? View image here https://i.stack.imgur.com/RrsGW.pnghtt ...

Tips for simulating the $timeout service with sinon?

I am looking to write a unit test for a method within an Angular controller that uses the $timeout service. However, I have been advised not to use inject in this scenario. Therefore, I need to mock $timeout on my own. Can someone guide me on how I can a ...

Repetitive attempts have led to the cancellation of the AJAX and PHP petition statuses

Whenever I click the button, I am trying to update a MySQL table using AJAX jQuery. Unfortunately, I am encountering a problem where the AJAX jQuery does not work properly sometimes. It starts off fine, but after a certain number of attempts, it stops work ...

Guide to creating a unique React component for displaying a single popup upon clicking with the ability to pass props to it

As someone who is still learning React, I decided to challenge myself by creating a Jeopardy game using this framework. My current idea is to have a popup appear when a player clicks on a box on the Jeopardy board, displaying the clue associated with that ...

What steps do I need to follow in order to incorporate and utilize an npm package within my Astro component

I have been working on integrating KeenSlider into my project by installing it from npm. However, I am encountering an error message that says Uncaught ReferenceError: KeenSlider is not defined whenever I try to use the package in my Astro component. Belo ...

A guide on implementing the MVC architecture in a web application with Node.js, Express, and PostgreSQL

I'm struggling with implementing the MVC architecture in my node web app, specifically when it comes to separating the model from the controller. Currently, I have the views properly organized (all my .ejs files) and I consider my app.js as the contr ...

PHP is not receiving AJAX POST requests through the $_POST method

I am currently working on a Firefox OS app and I am facing the challenge of using the OpenBadges API instead of PHP, which would have simplified the process. The issue I am encountering revolves around my data not being received by my PHP script after sen ...

Different ways to eliminate unnecessary items in an array

One task I have is to eliminate all duplicate elements within an array, as shown in the example below: var arr = [ {'seriesIndex':1,pointIndex:0}, {'seriesIndex':1,pointIndex:1}, {'seriesIndex':0,pointIndex:0}, ...

Tips for automatically closing SweetAlert after an AJAX request finishes

I recently implemented Sweet-alert into my Angular project. function RetrieveDataFromAPI(url) { SweetAlert.swal( { title: "", text: "Please wait.", imageUrl: "../../app/app-img/loading_spinner.gif", showConfirmB ...

What is the best way to limit a slash command to only be accessible to those with specific roles on a Discord server?

I am currently working on a discord bot using Discord.js V14 and implementing a command called "claimticket". However, I am facing an issue where I need to restrict this command to only members who possess one of the two specific roles that I have mentione ...

Unable to successfully retrieve the output from a function within an AJAX request

Hey, I'm having trouble getting the value from this function. It keeps returning undefined and I can't figure out why. Here's the code snippet: function getData() { axios.get('/task') .then(response => { ...

How to show dates in AngularJS using local formatting

One situation I'm dealing with involves setting a date for an event. The challenge is that the date picker needs to display the date in a localized format based on the country or region. I've been exploring various solutions in AngularJS, but so ...

What is the best way to showcase information from an external API in react js?

As I develop my new app, I am integrating API data from . This feature will enable users to search for their favorite cocktail drinks and display the drink name fetched from the API on the page. However, I am encountering an error that says "Uncaught TypeE ...

Guide to automatically filling in a form's fields with information from a database by clicking on a link

Currently, I have a form in HTML that is designed to gather user/member information. This form connects to a database with multiple columns, with two key ones being "user_email" and "invoice_id". Upon the page loading, the input for "user_email" remains hi ...

Issues with webpage responsiveness, width not adjusting correctly

Just completed coding my website and now I'm facing a new challenge. I am focusing on making it responsive for tablet screens (768px) starting with the header section, but for some reason, the modifications I make in the responsive.css file are not ta ...

Expanding the MatBottomSheet's Width: A Guide

The CSS provided above is specifically for increasing the height of an element, but not its width: .mat-bottom-sheet-container { min-height: 100vh; min-width: 100vw; margin-top: 80px; } Does anyone have a solution for expanding the width of MatBott ...

Retrieve the scrolling height in Vue.js 2 window

I need to apply the sticky class to the navbar when a user scrolls down, and remove it when they scroll back up. To achieve this, I am attempting to calculate the scrolled height. Currently, my code looks like: mounted(){ this.setUpRoutes(); wind ...