Skip to content

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

Answer

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())
}