Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

224
Visualizações
How to search an array of objects obtained by axios for an id? Vue 2

I am trying to verify if the user is inside that list that I capture by axios, the issue is that I have used the FILTER option but it always returns undefined or [], being that if the user exists in that array.

I can't think what else to do, because I validate if it is by console.log() the variable with which I ask and if it brings data.

    created() {
        this.getStagesDefault()
        this.getSalesman()
        this.getStagesAmountByUser()
    },
    methods: {
        async getSalesman(){
            const { data } = await axios.get('salesman')
            this.employees = data.data
        },
        getStagesAmountByUser(){
            console.log(this.user['id'])
            var objectUser = this.employees.filter(elem => {
                return elem.id === this.user['id']
            })

            console.log(objectUser)
        },

Console

enter image description here

Vue data

enter image description here

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

The method getSalesman is asynchronous, meaning that getStagesAmountByUser will start executing before getSalesman finishes.

Two ways to fix the problem:

  1. Await the getSalesman method, but you have to make the created method async as well. Change the code as follows:
async created() {
    this.getStagesDefault()
    await this.getSalesman()
    this.getStagesAmountByUser()
}
  1. Attach a .then to the getSalesman function, and start the next one inside the .then. Change the code as follows:
created() {
    this.getStagesDefault()
    this.getSalesman().then(() => this.getStagesAmountByUser())
}
about 4 years ago · Juan Pablo Isaza Relatório

0

getSalesman is an async method. At the time of the filter, the array being filtered is still empty.

this.getSalesman()            // this runs later
this.getStagesAmountByUser()  // this runs right away

Have the methods run sequentially by awaiting the async method:

await this.getSalesman()
this.getStagesAmountByUser()
about 4 years ago · Juan Pablo Isaza Relatório

0

You can avoid the inefficient clientside filtering if you pass the id to the backend and only select by that id.

Additionally, created only gets called once unless you destroy the component which is also inefficient, so watch when user.id changes then call your method again.

Plus don't forget you must wrap any async code in a try/catch else you will get uncaught errors when a user/salesman is not found etc, you can replace console.error then with something which tells the user the error.

{
  data: () => ({
    employee: {}
  }),
  watch: {
    'user.id' (v) {
      if (v) this.getEmployee()
    }
  },
  created() {
    this.getEmployee()
  },
  methods: {
    getEmployee() {
      if (typeof this.user.id === 'undefined') return

      try {
        const {
          data
        } = await axios.get(`salesman/${this.user.id}`)

        this.employee = data.data
      } catch (e) {
        console.error(e)
      }
    }
  }
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda