Having trouble accessing a property of an object in Vue?

I'm encountering an issue with accessing an object in Vue. Here is the code snippet:

App:

<template>
  <div class="container">
    <HeaderComp title="Task Tracker"></HeaderComp>
    <TasksComp :tasks="tasks"></TasksComp>
  </div>
</template>

<script>
import HeaderComp from "./components/Header.vue";
import TasksComp from "./components/Tasks.vue";

export default {
  name: "App",
  components: {
    HeaderComp,
    TasksComp,
  },
  data() {
      return {
        tasks: [],
      };
    },
    created() {
      const promise = fetch("https://jsonplaceholder.typicode.com/posts/1").then(
        (res) => res.json()
      );
      const handle = async () => {
        try {
          const data = await promise;
          this.tasks = data;
          console.log(data);
        } catch (error) {
          console.error(error);
        }
      };
      handle();
    },
};
</script>

Tasks:

<template>
  <main>
    <div v-for="task in tasks" :key="task">
      <TaskComp :task="task"></TaskComp>
    </div>
  </main>
</template>

<script>
import TaskComp from "./Task.vue";

export default {
  name: "TasksComp",
  props: ["tasks"],
  components: {
    TaskComp,
  },
};
</script>

Task:

  <p>{{ task.body }}</p>
</template>

<script>
export default {
  name: "TaskComp",
  props: ["task"],
};
</script>

I've fetched and handled a JSON response, converted it into a JavaScript Object, and set it as the value for the array tasks in the data() method. Within Tasks.vue, I iterate over each element (in this case just one, called task) within tasks. The individual task object is passed down as a prop to Task.vue, where the prop is accessed to display the body property within a paragraph tag.

However, despite all this setup, I'm unable to see the content of the body property. Any insights on what might be causing this issue would be greatly appreciated. Thank you!

I've verified that body is indeed a valid property, checked for potential type coercion or syntax errors, reviewed naming conventions, and even sought help from ChatGPT without success.

Answer №1

You specified that the variable tasks should be an array, but the API is returning an object instead. In order to add this new data to the tasks array, you need to use the push method.

const handle = async () => {
  try {
    const data = await promise;
    this.tasks.push(data);
  } catch (error) {
    console.error(error);
  }
};

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

When attempting to upload a picture using the camera, the file upload process is unsuccessful

Whenever I attempt to upload an image from my existing files, everything goes smoothly. However, if I try to select a file by directly clicking on the camera icon on my mobile device, it fails with a "CORS Error" message. I have tried adding and removing t ...

The Angular-Express combination is not being satisfied by the get request

`, I am a newcomer to the MEAN stack environment and I am struggling with fetching data from my Express server (which is set up with MongoDB) when a button is clicked. Even though the function associated with the button click is executed, the request does ...

Issue with parentNode.replaceChild not functioning properly in Internet Explorer 6

In my HTML file created with FCK editor, I attempted to replace an existing table element with a new one using the parentNode.replaceChild method. While this change was successful in Internet Explorer 8, it resulted in errors when viewed in IE6 and IE7. ...

What is the process for defining the origin in Javascript when using the DeepL API?

Any other solutions I can explore? Currently, I'm encountering a 403 response from the DeepL API due to a CORS issue while using axios. I attempted to address this by setting options using querystring but it was unsuccessful. The library mentioned in ...

Javascript function that sets the opacity to 0

Hello everyone, I'm new to SO and seeking some guidance on improving my post! I have a function that sets the opacity of an element to 0 in order to clear it. While this works fine, it becomes burdensome when dealing with multiple elements that requi ...

Showing user input on a separate page with the help of Ajax

I could use some guidance on how to display text sent via the post method to another page. My Requirements: To enter text in a textarea, and if a checkbox is selected, automatically send any changes made in the textarea to another page where the updated ...

Using Angular UI Router to Access $scope Beyond the Scope of the UI View

Looking for a way to access $scope outside the UI view in my todo app. The structure is simple, with three panels as shown in this design For the full code, visit here I need to access the to-do detail on the third panel using $rootScope, which currently ...

JavaScript Regular Expression for standardizing phone number input

I'm working with an input for a phone number in French format which can accept two different formats: 0699999999 +33699999999 There is currently no check for the length of the number. In the database table, the field is varchar 12, but shorter inp ...

Iterate over the controls within an UpdatePanel, and interact with JavaScript functions

I'm attempting to change all TextBoxes into labels on my page using the following code: foreach (Control ctrl in masterform.Controls) { if (ctrl.GetType() == typeof(TextBox)) { TextBox t = ctrl as TextBox; t.ReadOnly = true; ...

Issues with Bootstrap Navbar Dropdown functionality, including flickering or unresponsiveness

While working on a project, I incorporated the FlexStart Bootstrap Template. However, I encountered an issue with the Dropdown feature on the navbar. When hovering over the menu and submenu, they flicker incessantly. Despite investing a considerable amount ...

What could be causing the element to remain visible even after the mouse has left the area?

Is there a way to make the slider-paging disappear immediately when the mouse leaves the media-slider-wrap instead of it continuing to follow the cursor? It seems to linger if you move the cursor slowly out of the div... Any suggestions on how to fix this ...

Display whether the input is valid or invalid in the console depending on the value of the textArea

I am currently working on a JavaScript function that will display "valid input" in the console if all characters in a text box are non-alphabetic. However, if any alphabetic character is found in the text box, it should also display "valid input". This fun ...

What is the best way to trigger dependent APIs when a button is clicked in a React Query application

On button click, I need to call 2 APIs where the second query depends on the result of the first query. I want to pass data from the first query to the second query and believe using "react-query" will reduce code and provide necessary states like "isFetch ...

When the enter key is pressed in Spring and Vue.js, the request method 'POST' is not supported

One issue I am encountering is that when I click on the search button, everything works perfectly fine. However, if I try to press enter instead, an HttpRequestMethodNotSupportedException error is thrown. The strange thing is that I do not have a POST co ...

The callback function is required when using mongoose.find({}) operation

Recently, I've started exploring Node.js and mongoose. My current task involves querying objects from a mongo collection using find({}) with the following function: schema.statics.listAllQuizes = function listAllQuizes(){ Model.find({},function(err,q ...

Tips for accessing a PHP file across multiple domains

Currently, I am working with Core PHP and incorporating Javascript into my project. In this particular module, I am facing a challenge where I need to access data from one domain to another domain hosting the PHP file using Javascript for database storage. ...

Removing double quotes from a variable in Javascript: A quick guide

Looking to remove quotes from a variable: const sup = product[0]; // product[0] holds the value '8876532' I attempted two methods to remove the quotes but they were unsuccessful: sup.replace(/"/g, ""); and sup.replace(/["']/g, ""); If ...

Is it possible to remove filters from image links but still apply filters to links within the same div?

Is there a way to use hue-rotate to change the colors of my text links without affecting my image links? I have tried removing the effect from images only, but haven't been successful. Any suggestions on how to achieve this? I created a JavaScript but ...

Creating a file in JavaScript from text is a straightforward process that involves utilizing built

I'm currently working on some JavaScript code that will trigger a download of a file directly in the browser. I have successfully obtained the file content as bytes in a string, and now I need to pass this string to a function that will create a file ...

Providing uncompressed CSS/JavaScript files as needed

Optimizing your stylesheets and script files can enhance the performance of your website. However, there may be cases where you need to offer the non-minified versions of the files - whether it's for GPL compliance or to adhere to the optional code-o ...