Storing API information in an array using vue.js

Seeking assistance with this issue. I am attempting to fetch and save the list of users from an API into an array named "name". However, I have tried using a forEach loop without success. Any suggestions on how to resolve this problem would be greatly appreciated. Thank you!

Edit: I have wrapped the function, but it is still not functioning correctly.


import axios from 'axios'

export default {
  data() {
    return {
      info: null,
      name: []
    }
  },
  mounted() {
    axios
      .get('http://localhost:3000/api/users/', { mode: 'no-cors' })
      .then(response => (this.info = response.data))
      .then(() => info.data.forEach(element => {

      }))
      .catch(error => {
        console.log(error)
        this.errored = true
      })
      .finally(this.loading = false)

  }
}

Answer №1

After reviewing the code provided, it seems that there is an assumption made about the data contained in this.info. However, there are some issues in the code that need to be addressed:

1.

.then(response => (this.info = response.data))
.then(() => info.data.forEach(element => {

}))

It appears that info is undefined. It should likely be changed to this.info instead.

.then(response => (this.info = response.data))
.then(() => this.info.data.forEach(element => {

}))

If you prefer using arrow function syntax and returning an assignment expression, you can also do:

.then(response => (this.info = response.data))
.then(info => info.data.forEach(element => {

}))

However, this may not be ideal as some coding standards discourage returning assignment expressions due to potential readability issues when chaining promises.

2.

The use of forEach can impact Vue's reactivity. Vue may not detect changes with certain assignment syntax like this.name[i] = element. Instead, consider using array methods such as push, or better yet, functional programming operators like map and filter:

.then(() => (this.name = this.info.data.map(element => {

})))

Answer №2

Perhaps you need to reconsider the this reference, as callback methods may be in a different context. Here's a revised approach:

export default {
  data () {
    return {
      info: null,
      name: []
    }
  },
  mounted () {
    var that = this;
    axios
      .get('http://localhost:3000/api/users/', {mode: 'no-cors'})
      .then(response => (that.info = response.data))
      .then(info.data.forEach(element => {

      });)
      .catch(error => {
        console.log(error)
        this.errored = true
      })
      .finally(this.loading = false)

  }
}

Answer №3

Make sure to wrap the callback function in a function that accepts the info variable, like this:

import axios from 'axios'

export default {
  data () {
    return {
      info: null,
      name: []
    }
  },
  mounted () {
    axios
      .get('http://localhost:3000/api/users/', {mode: 'no-cors'})
      .then((response) => response.data.forEach(element => {

      }))
      .catch(error => {
        console.log(error)
        this.errored = true
      })
      .finally(this.loading = false)

  }
}

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

Updating the innerHTML of a frameset

I have a unique challenge that involves loading the frameset of www.example.com/2.html when accessing www.example.com/en/test/page.html. Successfully accomplished this task. Now, after loading 2.html in the frameset, I want to modify ".html" to ".html" t ...

`Need help setting the active class for a bootstrap navbar using Angular JS?`

In my bootstrap navbar, I have the following menu items: Home | About | Contact I'm looking to assign the active class to each menu item based on the current angular route. Specifically, how can I set class="active" when the angular route is at # ...

Photos not showing up in Venue Search results from Foursquare API

Currently, I am experimenting with the Venues feature in hopes of displaying certain information before delving into more specific queries. In this process, I am utilizing nodejs along with the following module: https://www.npmjs.com/package/foursquarevenu ...

How do you activate the background color for paragraphs <p> when a bootstrap button is styled with CSS?

In the code snippet provided below, dynamic creation of paragraphs with changing background colors and styles is demonstrated. One challenge faced in this script is maintaining the printed background colors for each dynamically generated paragraph. The is ...

Tips on saving all objects, even those that are repeated, in a JavaScript array

My goal is to store and display all objects, even if they are repeated, but the current setup only allows for storing unique values. The positive aspect is that it calculates the total by summing up all values, including duplicates. The Negative aspect is ...

Display invoices for multiple users logged in at the same time using Express.js

I have recently developed an invoice application using the MERN stack. The app works seamlessly when one user is logged in, but issues arise when multiple users try to access it simultaneously. In such cases, the invoices of the first user remain visible t ...

Adding options for a select tag from JavaScript can be accomplished by using the DOM manipulation methods

I am working on a form that includes drop-down menus. The options for the select tag need to change dynamically based on the id value. For instance, if the id is 1, the select tag options should be cat and dog. If the id is 2, the options should be apple ...

"Exploring three.js: Transforming a plane's orthogonal vector into a rotation matrix for the plane

I am trying to set the rotation of a plane by using three numbers representing the rotation in radians along the x, y, and z axes. Although I do not have these numbers, I do have a vector called 'myVec' which should be orthogonal to the plane af ...

Troubleshooting issue with Highcharts 3D rendering after using setState()

When working on implementing a 3d pie chart in React using react highchart, I encountered an issue. Whenever I utilize this.setState() inside the lifecycle method componentDidMount(), the 3d chart shifts from its original position to the right diagonally. ...

Error: Unable to initialize VueRouter as a constructor

In my app.js, I have the code snippet below: const routes = [ {path:'/home', component:home}, {path:'/department', component:department}, {path:'/employee', component:employee} ] const router = new VueRouter({ ...

Guide on downloading a PDF file with NodeJS and then transmitting it to the client

My goal is to download a PDF file using NodeJS and then send its data to the client to be embedded in the page. Below is the code snippet I am using to download the PDF file: exports.sendPdf = function(req, responce) { var donneRecu = req.body; va ...

Vue fails to receive updates from Firestore until the page is manually refreshed

I set out to develop a task tracker app using Vue. As I neared completion of the project, I encountered an issue - when adding a new task, it would not change the reminder status unless I reloaded the page. Here is the code snippet from my Home.vue file: & ...

After being deployed on Vercel, React is mistakenly redirecting to the incorrect file, although it functions properly when

I'm a beginner in JavaScript and I recently created a React project. Everything was working smoothly in local development until I deployed the project on Vercel. The issue is when a user clicks on the "about button," instead of showing 'about.htm ...

When loading a page for the first time, the Vue.js transition does not take effect

After setting up a navbar that switches between two components, I encountered an issue with the fade-in animation not running when the page is first opened. The animation only works when using the navbar links to switch components. Any suggestions on how t ...

Is there a way to generate random numbers that will create a chart with a general upward trend?

Are you looking for a solution to generate random numbers for charts that trend upwards and to the right? I am currently utilizing a JavaScript charting engine, so I will require numbers in JSON format eventually. However, I am open to alternative methods ...

Passing methods from child to parent components in Vue2 looped componentsHere is a

Currently, I am iterating through the root component, which contains a child component within it. <root-select v-for="offer in offers" > <child-options v-for="item in options" > </child-options> </root-select> However, when ...

The persistent redirection issue in Node.js - Middleware

Currently, I am in the process of developing a middleware using node js and express. The main objective of this middleware is to redirect users to a login page if they are not authenticated. Although the redirection to the login page works as intended, th ...

What can you tell me about Page Event functionality in Datatables?

Curious question -- I'm currently seeking a practical example of how to implement a 'page' event in a project utilizing DataTables. The provided documentation can be found here -- http://datatables.net/docs/DataTables/1.9.4/#page. Despite t ...

Getting the right AngularJS $scope within a controller for beginners

I am struggling to understand how to toggle the visibility of an element on a webpage using a controller. Below is a code snippet with an example - you can test it by clicking the "close edit" button (nothing happens): var appModule = angular.module(&a ...

various arbitrary visuals on an HTML5 canvas

I am attempting to randomly draw multiple images from an array on a canvas, but I'm struggling with iterating through the array and drawing them when the draw() function is called within a for loop. Here's my current code: // Call Draw particle ...