Fetching filtering options in Vue from an external data source

I am currently working with vue multiselect and I want to populate my options from an api source. When I follow the example in the official documentation, it works perfectly.

import Multiselect from 'vue-multiselect'

export default {
  components: {
    Multiselect
  },
  data () {
    return {
      value: [
        { name: 'Vue.js', language: 'JavaScript' }
      ],
      options: [
        { name: 'Vue.js', language: 'JavaScript' },
        { name: 'Adonis', language: 'JavaScript' },
        { name: 'Rails', language: 'Ruby' },
        { name: 'Sinatra', language: 'Ruby' },
        { name: 'Laravel', language: 'PHP' },
        { name: 'Phoenix', language: 'Elixir' }
      ]
    }
  }
}

However, when I try to replace the hardcoded options with my dynamic data, it fails to work as expected

data: function () {
            return {
                value: [],
                options: this.users
            }
        },
methods: {
       getUsers: function () {
            this.$http.get('/api/get/users').then(function (response) {
                    this.users = response.data;
                    this.updateUsers();
                    console.log(this.users)
                }, function (response) {
                    console.log(response)
                });
            },
            updateUsers: function () {
                this.options = this.users;
            }
        },
        created: function () {
            this.getUsers();
        }
    };

I have attempted calling the method using mounted, beforeMount, and beforeCreate but none of them seem to resolve the issue. The console displays the following errors:

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

I suspect the problem lies in how I am passing the options, however, I am unsure on the correct way to do so.

For the template, I am simply sticking to the default layout for now:

<div>
      <label class="typo__label">Simple select / dropdown</label>
      <multiselect v-model="value" :options="options" :multiple="true" :close-on-select="false" :clear-on-select="false" :hide-selected="true" placeholder="Pick some" label="name" track-by="name"></multiselect>
      <pre class="language-json"><code>{{ value  }}</code></pre>
  </div>

Answer №1

One strategy is to start with an empty array for options: []

data: function () {
        return {
            value: [],
            options: []
        }
    },

When the data comes from the backend, you can then populate the options array like this:

methods: {
   fetchUsers: function () {
        this.$http.get('/api/get/users').then( response => {
                this.options = response.data;

                console.log(this.users)
            }, function (response) {
                console.log(response)
            });
        },

Answer №2

When checking the console, an error message is displayed stating that prop

'options' was expected as an array but got undefined

This indicates that the mean value for this.options has not been assigned.

To resolve this issue, try the following:

Create a variable outside of the this.$http request.

let self = this;

Next, make the following replacement:

Change this.options to self.options

By making this adjustment, the code should now function properly.

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

Exploring the population with embedded RxJs queries

I'm struggling to find a solution to this particular issue. Imagine there is an object type described as follows: Box { Fruit[n]: { Kinds[n]: { id: string; name: string; } } } From an API call, I received a bo ...

Tap, swipe the inner contents of a <div> element without being inside it

(Make sure to check out the image below) I'm facing an issue with a <div> on my website. It's not taking up the full width of the page, and the scrolling functionality within the <body> is not working as expected. I just want the cont ...

Guide to retrieving a byte array from a server using JavaScript and converting it into a downloadable PDF

I am attempting to convert a byte array received from the server and download it as a pdf. The download functionality is working, but unfortunately, the file appears to be corrupt. My approach involves using JavaScript and vue.js. Function responsible fo ...

What other technique can I use to replace the creation of a jquery division?

I`m relatively new to all things related to web technologies and I am currently practicing and learning about them. On my practice page, I've experimented with various elements, including changing div heights based on the viewport height. Here's ...

Unexpected issue encountered for identifiers beginning with a numerical digit

Is it possible to select an element from a page with an id that begins with a number? $('#3|assets_main|ast_module|start-iso-date') Upon attempting to do so, the following error occurs: Uncaught Error: Syntax error, unrecognized expression: ...

What is the process for deploying a Vue app in a production environment?

Looking for guidance on deploying a Vue app in production? I've built the frontend of my project with Vue, and the backend uses Express.js APIs. Now, I'm ready to deploy it for production, but unsure of the process. After running "npm run build ...

FullCalendar jQuery caught in an endless loop

After successfully implementing drag and drop deletion, I encountered a new issue. Whenever I delete an event, the removal process functions properly but then the code gets stuck in a loop within the eventDragStop function causing the calendar to freeze ...

Send a property parameter to the Vue component

In my project using Vue and Laravel, I am trying to create a modal window with 2 tabs. The idea is to have two buttons, with each button linked to a specific tab that should open when clicked. These buttons are located in the blade template: <button ...

Utilizing intricate nested loops in Angular.JS for maximum efficiency and functionality

Struggling to work with data looping in Angular.JS, especially when it comes to specific formatting Let's illustrate what I'm aiming for using Java Here's a snippet: int itemCount = 0; for(int i = 0; i < JSON.length(); i = i + 3) { ...

Can three.js be effectively integrated into a Shopify store?

I've been working on incorporating a three.js object into my Shopify website for some time now. The main objective is to embed this 3D object onto the homepage. Below is the HTML/Liquid code I added to the homepage as a custom liquid section: <ca ...

Tips for halting the navigation bar when scrolling

Creating a Navigation Bar: <div class="navigation-bar"> <div class="item">Home</div> <div class="item">About us</div> <div class="item">Our Services</div> <div class="item">Contact us</div ...

How to efficiently export modules and handle return values in Node.js using async functions

In my current project, I am extracting data from a CSV file and performing some operations on it to create an object with the derived information. This function is implemented using module.exports for exporting. var csvtojson = require('csvtojson&apo ...

NEXT JS - Application renders twice due to rewrites in place

I'm currently working on a NEXT JS project and facing the issue of the app rendering twice! Challenge After implementing rewrites in next.config.js, the app is being rendered twice. Removing the rewrites solves the issue and only renders once. next ...

Ways to refresh a container

How do I update the box below... <div className="container team-member-tasks"> <header className="header-box"> <h1>Team Member Tasks</h1> ...after marking a task as complete using the script below. ...

Express 4 app.use not functioning properly

My backend setup is fairly straightforward with a few routes. I prefer to keep the route logic separate from the server.js file, but for some reason, when I make a POST request to the route, it returns a 404 error. In the server.js file: // Import necess ...

The error message in Next.js states: "Attempting to access properties of undefined (specifically trying to access 'indexOf')."

After successfully running the code below, I encounter an issue upon refreshing the page: TypeError: Cannot read properties of undefined (reading 'indexOf'). const [folders, setFolders] = useState([]); const [user] = useAuthState(auth); c ...

Verify whether a variable includes the tag name "img."

Currently, I am working with a variable that holds user input in HTML format. This input may consist of either plain text or an image. I am looking to determine whether the user has entered an image or just simple text. Here is an example of user entry: t ...

Guide to creating a new element using jQuery

Question regarding JQuery and a Dropzone plugin. Here is the HTML code: <form action="/file-upload" class="dropzone"> <div class="fallback"> <input name="file" type="file" multiple /> </div> </form> Desired styling ...

Deselect an HTML checkbox using a corresponding label's "for" attribute

Below is the html code I am using to display a checkbox with an image: <div class="testClass"> <input id="111" name="compare_checkbox" type="checkbox" /> <label for="111"> <i class="icon" aria-hidden="true"&g ...

What steps can I take to avoid unintentionally populating this object with undefined values?

This issue occurs when the variable level is initialized with the value 'undefined'. Although this code functions correctly in JavaScript, it encounters problems when using TypeScript. interface Find { level?: string; } let find: Find = {}; ...