Tips for obtaining an API with axios in nuxt.js

I am trying to fetch API information and populate a data table, but my code is throwing an error. The error messages can be seen below in the console.

The property or method "items" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.

Could someone please provide me with some advice?

Additionally, English is not my strong suit, so I would appreciate it if someone could help me correct any mistakes in my question.

<template>
  <v-app>
    <v-data-table dense :headers="headers" :item="items" class="elevation-1"></v-data-table>
  </v-app>
</template>

<script lang="ts">
import { Component, Vue } from "nuxt-property-decorator";
import axios from "axios";

@Component
export default class AxiosPractice extends Vue {
  items: object[] = [];

  headers = [
    { text: "id", value: "postId" },
    { text: "name", value: "name" },
    { text: "email", value: "email" }
  ];
  async mounted() {
    const response = await axios.get(
      "https://jsonplaceholder.typicode.com/posts/1/comments"
    );
    this.itmes = response.data.map((comment:any) => ({
      postId: comment.postId,
      email: comment.email,
      name: comment.name
    }));
  }
}
</script>

Answer №1

It appears that the object called response includes a property named data (refer to the documentation) which, in this scenario, contains an array of objects. If you aim to collect postId, email, and name for each comment within the items array, you might want to test out the following approach:

const response = await axios.get('https://jsonplaceholder.typicode.com/posts/1/comments');

this.items = response.data.map(comment => ({
  postId: comment.postId,
  email: comment.email,
  name: comment.name,
}));

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

Create a simulated API in Angular by utilizing JasonPlaceholder to retrieve information upon clicking a button

I am currently developing a dummy API using jsonplaceholder. I have managed to retrieve all posts after clicking a button, but now I want to display the user ID and title by default on page load. Additionally, when clicking on a post's title, I would ...

What is the process for defining a global variable within a module in Typescript?

I've already included a global value in my global JavaScript context: const fs = require('fs') For a specific reason, I need to include it in the global scope. Now, I want to create a .d.ts file to declare the global variable with a stron ...

ES5 compatibility issue with Vue.js export default

I'm currently in the process of building a website, and I've decided to use Vue with ES5 for some parts. One issue I've encountered is trying to pass data from a child component in Vue back up to the parent. The solution proposed to me was ...

Utilizing Nuxt with Vuetify theme's custom styling in the header section

I'm currently utilizing Vuetify alongside Nuxt.js, and I have successfully chunked out my CSS files to ensure they are not included on every page when running npm run generate. In order to accomplish this, I made the following adjustments: build: { ...

Cache for JSON Schema in VS Code

After updating to TypeScript 1.5 (now out of beta), I am eager to utilize the json schema helpers in VS Code. Upon configuring tsconfig.json, I noticed that only commonjs and amd module options are available, while umd and system are missing based on this ...

Having trouble with VueJS v-html to appendChild function - any solutions?

Experience the capabilities of HTML elements being stored in a data array in this engaging codesandbox demo. The code showcases how these elements are bound using v-html to a div, rendering them as child elements within that div. However, there seems to be ...

Parsing Devx DataGrid filter object for generating SQL queries

Sharing the solution here in case anyone finds it helpful. This code snippet helps convert the Devx Grid Filters into a group of objects to construct the query. ...

Using NavParams within a service component,

I'm facing a challenge in accessing NavParams within a provider, and simply importing NavParams is not solving the issue. Here's a brief overview of my application: users input their name and address, a pin is dropped on the map based on the add ...

Error encountered during conversion to Typescript for select event and default value

When trying to set the defaultValue in a Select component, TSlint throws an error - Type 'string' is not assignable to type 'ChangeEvent<HTMLInputElement> | undefined - for the code snippet below: const App = () => { const [ mont ...

No overload error encountered with TypeScript function call

I am working on an async function that communicates with the backend and I need it to handle axios error messages. My goal is to display these messages in a form. export async function register( prevState: string | undefined, formData: FormData ) { t ...

Is there a way to incorporate my getter into a computed property?

My Vuex Store is built using Vuex module decorators and I am facing an issue with using a getter for a computed property. Here is my code: @Module export default class WorkoutModule extends VuexModule { _workout: Workout; @Mutation startWork ...

Clicking on a date in Vue.js Fullcalendar

My goal is to retrieve a date value from the onDateClick function of fullCalendar using vue.js and then pass this data to a prop that can be stored in my backend via Laravel. However, I am encountering various undefined errors no matter how I approach th ...

Accessing form objects in Typescript with AngularJS

I am currently working with AngularJS and Typescript. I have encountered an issue while trying to access the form object. Here is the HTML snippet: <form name="myForm" novalidate> <label>First Name</label> <input type="text" ...

Is there a way to utilize MongoDB GridFS for uploading within a LoopBack 4 environment?

I'm a newcomer to Loopback 4 and I recently attempted to upload files using Loopback 4 to MongoDB GridFS. Although I referenced the file upload example from Loopback 4's documentation, I struggled to fully grasp it for customization purposes. pro ...

Vue table displaying a list of books with a button that allows users to easily send the title of the

Hey everyone, I am new to Vue and struggling with a certain task. I have two tables: Books and Booking. Books: ID, NAME, AUTHOR etc. Booking: ID, ID_USER, ID_BOOK I'm creating a page in Vue that displays all bookings, but the table only shows the BOO ...

Vue Slick Carousel does not have the capability to turn an image into a clickable link

I've encountered an issue while using vue-slick-carousel to create a slider. The problem arises when I wrap the image as a link - clicking on the image does not trigger a redirect. Interestingly, I have also wrapped a title under the image as a link a ...

Error: Unable to execute NGRX selector - x is not a valid function

I'm puzzled as to why I keep encountering a TypeError with this code. Is there something obvious that I'm overlooking? export const selectAllUsers = createFeatureSelector<ReadonlyArray<User>>('users'); export const select ...

using props as arguments for graphql mutation in react applications

Here is the structure of my code: interface MutationProps{ username: any, Mutation: any } const UseCustomMutation: React.FC<MutationProps> = (props: MutationProps) => { const [myFunction, {data, error}] = useMutation(props.Mutati ...

The Vue Swiper does not support inline containers in my code

I am facing an issue with the layout of my simple swiper in my vue app. The containers are not inline as expected, causing the second one to appear under the first. Additionally, I am struggling with making the slider element visible only within the viewpo ...

What is the best approach to defining document interfaces with Typescript and Mongodb?

Imagine a straightforward user database setup: // db.ts export interface User { _id: mongodb.ObjectId; username: string; password: string; somethingElse: string; } // user.ts import {User} from "../db" router.get("/:id", async (re ...