Getting News API and showcasing the information in Vuetify.js card components: A step-by-step guide

I'm trying to develop a news website by utilizing the News API for news data. I obtained an API Key from the official News API website, but my code is encountering some issues.

The error message reads:

TypeError: response.data.map is not a function

It seems like my map method is causing trouble, and I'm struggling to find a solution.

Below is the snippet of my code↓

<template>
  <v-card class="mx-auto" max-width="600">
    <v-system-bar class="indigo darken-2" dark>
      <v-spacer />
      <v-icon>mdi-window-minimize</v-icon>
      <v-icon>mdi-window-maximize</v-icon>
      <v-icon>mdi-close</v-icon>
    </v-system-bar>
 
    <v-toolbar color="indigo" dark>
      <v-app-bar-nav-icon></v-app-bar-nav-icon>
      <v-tool-bar-title>Discover your news</v-tool-bar-title>
      <v-spacer />
      <v-btn icon>
        <v-icon>mdi-mgnify</v-icon>
      </v-btn>
    </v-toolbar>
 
    <v-container fluid>
      <v-row dense>
        <v-col v-for="card in cards" :key="card.title" :cols="card.flex">
          <v-card>
            <v-img :src="card.urlToImage" height="200px">
              <v-card-title v-text="card.author"></v-card-title>
            </v-img>
            <v-card-actions>
              <v-spacer />
 
              <v-btn icon>
                <v-icon>mdi-heart</v-icon>
              </v-btn>
              <v-btn icon @click="send">
                <v-icon>mdi-bookmark</v-icon>
              </v-btn>
              <v-btn icon>
                <v-icon>mdi-share-variant</v-icon>
              </v-btn>
            </v-card-actions>
          </v-card>
        </v-col>
      </v-row>
    </v-container>
  </v-card>
</template>
<script lang="ts">
import { Component, Vue } from "nuxt-property-decorator";
import axios from "axios";
 
@Component({})
export default class extends Vue {
  cards:[]=[]
    async created(){
        const response = await axios.get('https://newsapi.org/v2/everything?+ 'My API Key'');
        this.cards = response.data.map((comment: any) => ({
      title: comment.articles.title,
      author: comment.articles.author,
      urlToImage: comment.articles.urlToImage,
      flex:6
    }));}
 
  async send() {}
}
</script>

Answer №1

The API response showcasing news data through response.data would appear in this manner:

{
  "status": "ok",
  "totalResults": 4239,
  "articles": [
    {
      "source": {
        "id": null,
        "name": "Boing Boing"
      },
      "author": "Boing Boing's Shop",
      "title": "Should you get a VPN or SmartDNS service? Either way, KeepSolid has you covered.",
      "description": "For years, you've heard the steady drumbeat. You need to have a VPN to protect yourself online. It's been drilled into all of us for more than a decade. But in the wake of VPN, KeepSolid, one of the world's most respected VPN providers, has jumped into the ma…",
      "url": "https://boingboing.net/2020/08/23/should-you-get-a-vpn-or-smartd.html",
      "urlToImage": "https://i2.wp.com/media.boingboing.net/wp-content/uploads/2020/08/sale_32867_article_image.jpg?fit=1200%2C800&ssl=1",
      "publishedAt": "2020-08-24T02:00:00Z",
      "content": "For years, you've heard the steady drumbeat. You need to have a VPN to protect yourself online. It's been drilled into all of us for more than a decade.\r\nBut in the wake of VPN, KeepSolid, one of the… [+4167 chars]"
    },
    {
      "source": {
        "id": null,
        "name": "Deseret News"
      },
      "author": "Art Raymond",
      "title": "Swindlers take University of Utah for nearly $500K in ransomware attack - Deseret News",
      "description": "SALT LAKE CITY — The University of Utah was stung by cybercriminals for almost $500,000 in ransom following a July attack that gave the state’s flagship institution the choice of sacrificing private student and employee data, or paying up and hoping the infor…",
      "url": "https://www.deseret.com/utah/2020/8/21/21396174/cyber-swindlers-take-university-of-utah-for-nearly-500k-in-ransomware-attack"",
      "urlToImage": "https://cdn.vox-cdn.com/thumbor/kzJ07E_qBo3TGMYfL7jhxf16VU8=/0x136:2400x1393/fit-in/1200x630/cdn.vox-cdn.com/uploads/chorus_asset/file/20790900/University_of_Utah_DNSTOCK_KM_2018.jpg"",
      "publishedAt": "2020-08-24T01:43:00Z",
      "content": "SALT LAKE CITY The University of Utah was stung by cybercriminals for almost $500,000 in ransom following a July attack that gave the states flagship institution the choice of sacrificing private stu… [+4553 chars]"
    }
  ]
}

Utilize Array.prototype.map solely on arrays. Ensure your code employs this function on the array of response.data.articles:

this.cards = response.data.articles.map(article => ({
  title: article.title,
  author: article.author,
  urlToImage: article.urlToImage,
  flex: 6,
}))

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 are the distinct roles of the server and client in a Nuxt SSR application?

Currently, I am working with Nuxt 2.13 and developing an e-commerce platform. However, I have encountered some server resource issues where the initial site load is taking longer than expected (although route changes are fast and smooth). I am curious to ...

lint-staged executes various commands based on the specific folder

Within my project folder, I have organized the structure with two subfolders: frontend and backend to contain their respective codebases. Here is how the root folder is set up: - backend - package.json - other backend code files - frontend - p ...

Navigating from the Login Page to the Dashboard in Vue.js following successful token validation

I am facing an issue with the code that is supposed to redirect the User to the dashboard page if they have a token. Despite generating a JWT token from my Spring Boot backend and sending it to Vue for processing, the redirection is not working as expect ...

The system is unable to locate a supporting entity with the identifier '[object Object]', as it is classified as an 'object'

I'm currently working on an Angular 2 application where I am retrieving data from an API and receiving JSON in the following format. { "makes": null, "models": null, "trims": null, "years": null, "assetTypes": { "2": "Auto ...

After verifying the variable is an Array type, it is ideal to utilize the .forEach()

Within my generic functional component, I have the following code snippet: if(Array.isArray(entry[key as keyof T]) { entry[key as keyof T].forEach((item: T) => { ... }); } The variable key is a string that dynamically changes. However, when attempt ...

Is the data missing in the initial request?

After creating a function that returns an object with mapped values, I encountered an issue. The second map is undefined the first time it runs, causing my vue.js component to display data from the first map but not the cutOff value. Strangely, when I re ...

Observing rxjs Observable - loop through the results and exit when a certain condition is met / encountering an issue with reading property 'subscribe' of an undefined value

I'm fairly new to working with rxjs and I've been struggling to find the right operator for what I want to achieve. Here's my scenario - I have an array that needs to be populated with results from another observable. Once this array has en ...

Jest stops execution after an async method is called

When a click event triggers an async method in my code, it makes a call to an API and processes the response as shown below: async confirmName () { const {name, description} = this.form; const [data, error] = await Pipelines.createPipeline({name, d ...

The `findOne` operation in Mongoose fails to complete within the 10000ms time limit

Encountering this error on an intermittent basis can be really frustrating. I am currently using mongoose, express, and typescript to connect to a MongoDB Atlas database. The error message that keeps popping up reads as follows: Operation wallets.findOne() ...

Combining various POST requests by matching the common value in each array. (Angular)

Here are the two different sets of data: "statusCode": 200, "data": [ { "color": { "id": "1111", "name": null, "hex&quo ...

What is the reason behind Typescript errors vanishing after including onchange in the code?

When using VSCode with appropriate settings enabled, the error would be displayed in the following .html file: <!DOCTYPE html> <html> <body> <div> <select> </select> </div> <script&g ...

How can I set a document ID as a variable in Firebase Firestore?

I recently set up a firestore collection and successfully added data (documents) to it. Firestore conveniently generates unique document ids for each entry. Inserting Data this.afs.collection('questions').add({ 'question': message, &a ...

Ensure that the output of a function in Typescript matches the specified data type

Looking for a way to inform TypeScript that the output of a function will always meet the type requirements of a variable, therefore avoiding any error messages? Type 'string | Date' is not assignable to type? For example: const getStringOrDat ...

Despite using Enzyme to locate a component again, the expected prop value is still not being returned

Two components are involved here - a modal and a button that is meant to open the modal by setting its isOpen prop to true. The initial state of the modal is set to false, but when the button is clicked, it should change to true. While everything works fi ...

Tips for utilizing jest.mock following the removal of @types/jest (^jest@24)

After upgrading from version 7 to version 8 of @angular-builders/jest, I followed the instructions provided in the migration guide which advised removing @types/jest since it now comes bundled with Jest v24. Additionally, changes were made to my tsconfig a ...

Tips for showcasing images consistently in a V-Card with uniform sizes

Hey there, I'm facing a bit of a challenge that I can't seem to crack. Apologies for not sharing my entire code. So here's the problem: I'm working on this: <v-card> <v-img :src=“{{person.png}}”</v-img> <v-card& ...

Encountering a SassError while trying to create unique themes with Angular Materials

I'm currently in the process of designing a unique theme for Angular Materials by following the instructions provided in this guide:https://material.angular.io/guide/theming#defining-a-custom-theme However, I've encountered an issue while attemp ...

When the key property is utilized, the state in react useState is automatically updated; however, for updating without it, the useEffect or a

I am working on a component that looks like this: import React, { useState } from "react"; import { FormControl, TextField } from "@material-ui/core"; interface IProps { text?: string; id: number; onValueChange: (text: stri ...

Refrain the output of a v-for loop in vueJS

Seeking a simple solution - I have a list of members that I need to iterate through using v-for. However, I only want to display the first two results. Is there a way to limit the displayed results to just the first 2? members = [ {id : 1, name: 'Fran ...

Selecting the appropriate color code based on a specified value

If the value of zoneTempDiff1 falls below 1.5, consider using temp: 1 color. If it exceeds 1.5, opt for temp: 2 color. The same logic applies to all different values such as -1, -2, 0, 1, 2, 3, 4, or 5, each corresponding to a specific color code. In cas ...