How to add the answer to an Axios request in an Array?

Asked

Viewed 65 times

0

I am trying to put the answer to an Axios request inside an array, but I am receiving as a response a strange structure, as I will show in the following image:

inserir a descrição da imagem aqui


I created an Array, added my own name and soon after I tried to make a loop where I add the items referring to the Axios request response. But in response I get this structure from the image above, and the strangest thing, when I try to access from position 4 forward, it returns me "Undefined" Does anyone know what it can be?

Here is the code:

var nomes: Array<String> = [];
nomes.push("Abner")
nomes.push("Matheus")
nomes.push("Gomes")
nomes.push("Silva")
mat.map(r => {
  Axios.get(`/pessoal/pessoa/${r}/buscarCursos`).then(response => {
     nomes.push(response.data.toString())
  })
})
console.log(nomes)

1 answer

0

By taking out the function toString and placing some attribute-field that returns from Axios, it will add the return inside the names array, giving sequence. After "Silva", comes the amount of iteration in mat, if you have an array with 10 items, it will return the field of 10 adding 14 items, counting in array will be 13 because it starts at 0.

If you want to return the subjects next to the students' names, use Object.

const mat = ['6e66784-0e1c-cf1-6708-848c66518f6f', '2bdcedb-c25a-3f1e-443e-b6a2463d856']

let nomes = Array()
nomes.push('abner')
nomes.push('matheus')

mat.map(item => {
  axios.get(`http://localhost:3333/projects/${item}`).then(response => {
    Object.assign(nomes, { materia: response.data.name })
    console.log(nomes)
  })
})

Browser other questions tagged

You are not signed in. Login or sign up in order to post.