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

https://i.sstatic.net/gaeCe.png

Vue data

https://i.sstatic.net/vHkCV.png

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

Render a component in certain routes based on specific conditions in React

This is my Index.js ReactDOM.render( <React.StrictMode> <Provider store={store}> <Router> <App className="app-main" /> </Router> </Provider> </R ...

The file that is currently being downloaded has the .pptx extension, but it is being

Take a look at this code snippet: const generateDownload = ({ link, data, title, settings })=> { const newLink = document.createElement('a'); const blobUrl = link || URL.createObjectURL(new Blob([data], settings)); newLink.setAt ...

Utilizing a custom keyboard with Jquery for a recurring function

It seems like I might be missing something simple here, as I am following the code tutorial provided in the link below: The goal of this project is to create a popup keyboard for a touch screen. Although I have made some modifications for specific purpose ...

Autocomplete feature in MUI allows filtering to begin after typing at least 3 characters

I've encountered an issue with the Autocomplete MUI component I'm using to filter a list of checkboxes. The popup with options should remain open at all times, but I only want the filtering to be triggered when the user input is more than 3 chara ...

I am having difficulty accessing the dataset on my flashcard while working with React/Next JS

I'm currently developing a Flashcard app that focuses on English and Japanese vocabulary, including a simple matching game. My goal is to link the two cards using a dataset value in order to determine if they match or not. When I click on a flashcar ...

The HTML code may fade away, but the JavaScript is still up and running behind the

Switching between different div elements in my HTML document is a challenge. Here's the code I currently have: <div id="screen1" class="current"> <div id="press_any_key_to_continue"> <font style="font-family: verdana" color="yellow ...

What is the best way to display a loading animation until the entire wizard has finished loading in the jQuery-steps

I need help with implementing a loading animation using the jQuery-steps plugin in my wizard type form. I want the animation to be displayed until the entire wizard has loaded completely, but I'm unsure of how to enable this feature as there is a labe ...

ClassSerializerInterceptor in NestJS does not show the _id field

I am encountering an issue with properly exposing the _id when using the Serializer. Here is my current setup: @UseInterceptors(ClassSerializerInterceptor) @SerializeOptions({ strategy: 'excludeAll' }) This is how I defined the Class: export cl ...

Error in Webpack 5: Main module not found - Unable to locate './src'

When trying to build only Express and gql server-related files separately using webpack5, an error occurs during the process. ERROR in main Module not found: Error: Can't resolve './src' in '/Users/leedonghee/Dropbox/Project/observe ...

Switch out multiline text with javascript

Could someone assist me with this question? I am attempting to locate and replace specific code within a JavaScript file. The code is included in an AJAX response that contains a significant amount of HTML code. After retrieving the AJAX response, I stor ...

Insert a new class within the container div

I am looking to insert a 'disabled' class within a parent div named 'anchorxx' https://i.sstatic.net/3KRMQ.png The disabled class div can be located anywhere within the anchorXX divs Is it achievable using jquery? I am unsure how to ...

Node.js poses a challenge when it comes to decoding incoming request data

I am attempting to create a sample login page using the combination of node, express, and angularjs. Displayed below is my login view: <div class="login-page"> <div class="login-page-content"> <div style="margin-top:30px;padding:10px;w ...

Is there a way for me to access the source code of elements within React Native?

Currently, I am working on writing code using React Native and compiling it in Android Studio with an emulator. When I press ctrl+m on the emulator and select "show inspector" to click on elements, I am unable to see which line of code corresponds to the s ...

What could be causing this code to fail in making changes to the HTML document?

I tried incorporating the following code into my website: $('.feed-item').append('<p> This is paragraph element. </p>'); You can view it on this page: Test Unfortunately, the code does not seem to be functioning properly. ...

Cypress, encountering issues with If/Else or Switch Case implementations

My current challenge involves adding else if / switch case in my test. The issue I am facing is that when the initial 'if' condition fails, it does not go into the else if statement. This problem persists in both else if statements and switch cas ...

Caution when using a React form: Value of `true` has been detected for a non-boolean attribute `validate`

I am trying to address a warning message that I have received index.js:1 Warning: Received true for a non-boolean attribute validate. If you want to write it to the DOM, pass a string instead: validate="true" or validate={value.toString()}. I ...

Exploring the chosen choice in the Material Design Lite select box

Consider the following scenario. If I want to extract the name of the country chosen using JavaScript, how can this be achieved? <div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label getmdl-select getmdl-select__fullwidth"> ...

Can you help me with sorting asynchronous line points for KineticJS?

For the past couple of days, I've been grappling with a peculiar issue that I found difficult to articulate in the title. The challenge I'm facing involves a KineticJs Line, which contains an array of points (line.attrs.points) represented as ob ...

Is it possible that jest is unable to catch the exception?

I have a simple function that looks like this: function foo({ platform }) { if (platform === 'all') { throw new Error('Platform value can only be android or ios'); } return `${platform}`; } After writing unit tests, the re ...

Setting the default month for the Vuetify date picker

I am currently utilizing the Date Picker component with a v-model set as an array of dates: ['2022-04-10', '2022-04-11']. Despite my dates falling in April 2022, I want to establish the default month as May (to have the Date Picker dis ...