Exploring the process of searching for an id within an array of objects received through axios in Vue 2

I am currently working on verifying whether the user is included in the list that I retrieve using axios. However, I am facing an issue where the FILTER option I have used consistently returns undefined or [], even when the user does exist in the array.

At this point, I am at a loss for what else to try. I have tried validating by checking the data returned with console.log() but haven't been able to make progress.

    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

Vue data

Answer №1

One key point to note is that the method getSalesman operates asynchronously, implying that getStagesAmountByUser will commence executing before getSalesman completes.

To address this issue, there are two possible solutions:

  1. Utilize the await keyword with the getSalesman method, but ensure that the containing method (in this case created) is also marked as async. Modify the code as shown below:
async created() {
    this.getStagesDefault()
    await this.getSalesman()
    this.getStagesAmountByUser()
}
  1. Implement a .then callback after the getSalesman function call, and trigger the subsequent action inside this callback. Adjust the code as follows:
created() {
    this.getStagesDefault()
    this.getSalesman().then(() => this.getStagesAmountByUser())
}

Answer №2

fetchSalesperson is a function that returns data asynchronously. When the filter is applied, the array being filtered is still empty.

this.fetchSalesperson()            // this operation occurs later
this.calculateTotalSales()  // this operation occurs immediately

To ensure that the functions are executed sequentially by waiting for the asynchronous method to complete:

await this.fetchSalesperson()
this.calculateTotalSales()

Answer №3

To optimize performance, it is recommended to pass the id to the backend for selecting data instead of filtering on the clientside.

Remember that the 'created' method is only called once unless the component is destroyed, so be mindful of updating your method when the user.id changes.

Always wrap asynchronous code in a try/catch block to handle errors gracefully, ensuring a smooth user experience even when a user or salesman is not found. You can also customize error messages instead of relying on console.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)
      }
    }
  }
}

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

Retrieve the chosen option index using AngularJS

It is common knowledge that a select list can have multiple options, each starting from [0]. For example: [0]<option>E.U</option> [1]<option>India</option> [2]<option>Peru</option> In my Angular application, I am using ...

Is it possible to retrieve the controller path for an AJAX request from within a partial view?

Looking for a solution to fully decouple and reuse a partial view that allows users to select dates and filter results based on those dates. This widget can be used on multiple pages, so I wanted to add event listeners that would submit the form within the ...

Troubleshooting: Issues with Mixins in Vue Test Utils and Jest

I am facing an issue with a local Vue app where I have added a method to all components using mixins. However, when I mount the app, the method does not seem to be mixed for child components. Below is my code snippet: import { createLocalVue, mount } from ...

What are the steps to successfully integrate Vuetify 2.3 or any other packages into a Vue 3 Project?

How can I properly register Vuetify in my main.js file without using Vue alias? After importing Vuetify, all of my components are hidden. Dependencies: "vue": "^3.0.0-rc.7", "vue-router": "^4.0.0-0", &quo ...

Leveraging v-model with a bespoke component

Currently, the input field is empty when I start typing and I want to see this data in the console. What could be the issue with my code? HTML: <products-list v-model="product.name" v-on:keyup="productName"></products-list> ...

Enhance with Laravel combined with AngularJS

I've encountered some issues with the "edit" part while working on a Laravel + AngularJS CRUD application. An internal server error is being displayed, and I'm seeking assistance to understand its cause. Error "GET localhost/crudtcc/public/ap ...

An error is displayed when attempting to construct an express-react application

Currently, I am working on a project in React and ExpressJS that was previously worked on by someone else. When attempting to run the command npm run build An error is displayed in the project: https://i.stack.imgur.com/PsfpS.png How can I resolve thi ...

Deactivating and activating an HTML input button

So I was tinkering with this cool button: <input id="Button" type="button" value="+" style="background-color:grey" onclick="Me();"/> I've been wondering, how can I conveniently control its state of being disabled or enabled? Initially, I attem ...

Enhance your dynamic php page with the use of a light box feature

Hey, I have created a PHP page that dynamically reads images from a folder and displays them on a gallery page. However, I am facing some issues - I am unable to link an external CSS file and I have to include all the CSS within the HTML. Additionally, I c ...

What is the best way to showcase page content once the page has finished loading?

I'm facing an issue with my website. It has a large amount of content that I need to display in a jQuery table. The problem is that while the page is loading, all rows of the table are showing up and making the page extremely long instead of being sho ...

What steps can be taken to resolve the issue with "vnode.context[binding.expression]"?

Currently, I am in the process of developing an application using VueJS. In one of my components, I am trying to detect when a user clicks outside of it. After doing some research, I came across a potential solution on Stack Overflow at this link. However, ...

Vue.js: How to Handle Web Page Updates When State Changes in Nested Objects

Vue.js offers methods like Vue.set for adding and Vue.delete for deleting, but there is no specific method for 'update'. Instead, you can use Object.assign. This works well unless there are changes in nested objects. Is there a function in Vue th ...

Storing Images in MongoDB with the MEAN Stack: A Guide using Node.js, Express.js, and Angular 6

I am currently working on developing a MEAN Shop Application, and I have encountered an error while attempting to store the product image in MongoDB. typeError: cannot read the property 'productimage' of undefined Below is the route function fo ...

Is there an improved guide available for using Netbeans' new language support plug-in?

Recently, I've started working with a new server side language that is based on Javascript. It has similar functionalities to PHP, but uses Javascript syntax for processing server responses and handling logic. In terms of text editors, Netbeans is my ...

"Having issues with Django not properly applying the JavaScript and CSS files I've linked in

I have completed my project and organized all the necessary files, including index.html, css, js, and settings.py within the appropriate folders. I am encountering an issue with applying a pen from the following source: CodePen index.html <!DOCTYPE h ...

Controls that shift a DIV in either direction

I've been working on making a div scroll left or right with either a mouseover effect or click, but I can't seem to figure out what's going wrong. My initial attempt was straightforward: <body> <div id="innerscroll"></div> ...

AngularJS variable assignment with HTTP GET operation

The angular filter I have set up is functioning perfectly: categorieFilter = angular.module("categorieFilter", []) categorieFilter.controller("catFilter", ["$scope", "store", function($scope, store){ $scope.search = ""; $scope.products = []; $ ...

Activate Vuetify to toggle a data object in an array list when the mouse hovers over

I'm currently working on a project where I need to toggle a Vuetify badge element for each item in an array when the containing div is hovered over. While I've been able to achieve a similar effect using CSS in a v-for loop with an array list, I ...

Having trouble getting the expected transition effects to work with Vue.js

Currently, I have a display of lists of items through the use of v-for. Initially, only the summary section of each item is visible. Upon clicking on an item, the details section is supposed to appear. This functionality is achieved by adding or removing ...

Unprepared for handling JSON data with JavaScript and jQuery

{ "Items": [ { "location": "bakery", "item1": "milk", "item2": "bread" } ], } Currently, I am encountering difficulties in parsing a JSON object and receiving the following error: Error: Unca ...