Vue.js components may not always display the data that has been fetched

Within a Laravel view, there is a component where the data in the select tag sometimes doesn't show up. It's quite strange as it randomly displays the data and other times it doesn't. There are no errors being logged in the console or the view. Here is the code for the component:

<template>
<div class="row">
    <div class="col-md-12 text-center" v-if="!loaded">
        <br>
        <i class="fas fa-spinner fa-2x fa-pulse"></i>
    </div>
    <div class="col-md-12" v-else>
        <div class="row">
            <div class="col-md-6" >
                <label for="subjects">{{ trans('strings.choseSubject') }}</label>
                <select name="subjects" id="subjects" class="form-control selectpicker filter-input"
                        data-live-search="true" data-style="filter-input" @change="addSubject">
                    <option value="">{{ trans('strings.choseSubject') }}</option>
                    <optgroup v-for="category in subjects" :label="category.name" :data-catID="category.id">
                        <option :value="subject.id" v-for="subject in category.subjects">{{ subject.name }}</option>
                    </optgroup>
                </select>
            </div>
            <div class="col-md-6">
                <div class="other-subject-form d-none">
                    <label for="otherSubject">{{ trans('strings.choseSubject') }}</label>
                    <input type="text" class="form-control filter-input" id="otherSubject" name="otherSubject">
                </div>
            </div>
            <div class="col-md-12">
                <br>
                <hr>
                <br>
            </div>
            <div class="col-md-12">
                <div class="btn-group mb-2" v-for="subject in user_subjects">
                    <button type="button" class="btn btn-danger" :data-subjectID="subject.id" @click="deleteSubject" style="font-weight: bold">X</button>
                    <button type="button" class="btn btn-blue" disabled style="opacity: 1 !important;">{{ subject.name }}</button>
                    &nbsp;
                    &nbsp;
                </div>
            </div>
        </div>
    </div>
</div>

Description of how the component functions:

  <script>
export default {
    data() {
        return {
            loaded: false,
            subjects: [],
            user_subjects: []
        }
    },
    methods: {
        getSubjects: function () {
            axios.get('/t/get/subjects').then(function (response) {
                console.log(response);
                response.data.categories.map((value) => {
                    const category = {
                        id: value.id,
                        name: value.name,
                        subjects: value.subjects
                    };
                this.subjects.push(category);
                });
            }.bind(this));
            this.loaded = true;
        },
        getUserSubjects: function () {
            axios.get('/t/get/teacher/subjects').then(function (response) {
                this.user_subjects = [];
                response.data.subjects.map((value) => {
                    const subject = {
                        id: value.id,
                        real_id: value.subject.id,
                        name: value.subject.name
                    };
                $('#subjects').find('option[value="'+value.subject.id+'"]').remove();
                this.user_subjects.push(subject);
                });
                $("#subjects").selectpicker("refresh");
            }.bind(this));
            this.loaded = true;
        },
        addSubject: function (e) {
            var id = e.target.value;
            if(this.user_subjects.length<10)
            {
            axios.post('/t/subject/add', {
                subject_id: id,
            }).then(function (response) {
                this.getUserSubjects();
            }.bind(this));
        }
        else
        alert("You reached your maximum subjects! You can delete the subjects you don't need by pressing on the X button beside each subject");
        },
        deleteSubject: function (e) {
            var id = e.target.getAttribute('data-subjectID');

            axios.post('/t/subject/delete', {
                subject_id: id,
            }).then(function (response) {
                // var alasql = require('alasql');
                // this.user_subjects = alasql('DELETE FROM ? WHERE `id` = '+ id , [this.user_subjects]);
                this.user_subjects = this.user_subjects.filter(function (obj){
                    return obj.id != id
                });


                $('#subjects optgroup[data-catID="'+response.data.category_id+'"]').append($('<option>', {value:response.data.id, text: $('html').attr('lang') === 'ar' ? response.data.name_ar : response.data.name}));
                $("#subjects").selectpicker("refresh");
            }.bind(this));
        }
    },
    computed: {},
    created() {
        Vue.prototype.trans = string => _.get(window.i18n, string);
        console.log(this.subject);
        this.getSubjects();
        this.getUserSubjects();
        if(this.subjects == null){
            this.$forceUpdate();
        }
    }
}

In the blade view, the component is included like this :

<br>
                    <subjects-selector></subjects-selector>
                    <br> <br>

Any insights into why this peculiar behavior is occurring? The rendering seems inconsistent with a 50/50 chance...

Answer №1

I encountered a similar issue before, which was due to duplicate or missing keys in the v-for loops. One possible solution is to include the :key attribute in your code:

<optgroup v-for="category in subjects" :key="category.id" :label="category.name" :data-catID="category.id">
    <option :value="subject.id" v-for="subject in category.subjects" :key="subject.id">{{ subject.name }}</option>
</optgroup>

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

Vue specifies the location of the index.html file

I'm new to working with Vue and node, and I'm attempting to insert a global value in my project by placing my index.html in a public directory. After creating the project, I noticed that the public src folder was not generated, but I could still ...

Converting a string into an array of JSON objects

I am currently attempting to send data to my NodeJS server using the HTTP protocol (vue-resource). The goal is to send an array of JSON objects structured like this : [{"name":"Charlotte","surname":"Chacha","birth":"2000-04-02"},{"name":"Michael","surname ...

What is the best way to check a configuration setting in vue.config.js from srcmain.ts?

I am updating my vue application to include code that will automatically redirect from HTTP to HTTPS when accessing the page. (I understand that configuring this in the webserver is a better practice, but it doesn't hurt to be extra cautious) if (loc ...

Access your Node.js application by using the address on your Laravel Forge server

My Node.js app is successfully running on Laravel Homestead, but I now need to transfer it to the server. I am using Laravel Forge for server provisioning and all the necessary Node packages are already installed. While testing locally, I use Homestead&ap ...

Leveraging Environment Variables in Vue.js

I've been diving into the official documentation, but haven't come across any information regarding environment variables. While there are community projects that offer support for this feature, they seem a bit excessive for my needs. I'm cu ...

Upon executing npm install in my Laravel project, an error message promptly appears stating: "npm WARN deprecated [email protected]: gulp-util is deprecated - replace it."

Recently, I set up a brand new Laravel Project. After executing the command: php artisan preset vue, when I tried running npm install, an error occurred that stated: npm WARN deprecated [email protected]: gulp-util is deprecated - replace it, followi ...

Vue CLI Plugin Electron Builder displays a completely empty screen after compiling

After building my electron app using this specific plugin, I encountered a frustrating issue where the installed package would only display a blank, white screen. Despite setting up the window to open dev tools in the built version, inspecting the page rev ...

Exploring the possibilities of updating the version dynamically in package.json file

Upon receiving version 1.0.1 (server_version) from the server I make sure process.env.version matches server_version If they are the same, I update process.env.version to server_version. But unfortunately, this process cannot be done from the client side. ...

Transmitting data from express server to vue.js interface

Hey there, I am facing a bit of a complex situation and could really use some help. Here's what I've got: an application split into server-side using node/express and client-side with Vuejs. The issue arises when I try to create a user on the ba ...

The ideal structure for a Vue app

As a newcomer to Vue, I've been exploring different guidelines on how to use it effectively. In one resource here, the project was structured with separate directories for assets, components, routes, services, and views within a 'src' direct ...

What are the steps to crawl and save content from multiple websites simultaneously?

My project involves creating a webpage that can crawl multiple other webpages and integrate the data. I am using node.js & vue.js for this purpose. By utilizing puppeteer & cheerio, I have successfully been able to crawl a single page and store its data i ...

Looking for an efficient method to initiate vagrant configuration seamlessly with just a click?

When setting up different VirtualBoxes on Linux, I rely on using vagrant. My objective is to simplify the process for my colleagues by allowing them to visit an intranet site where they can choose which VirtualBox they would like installed on their machin ...

Why does Request-Body(req.body) display a value while Request-QueryParams(req.queryParams) returns null?

Using vuejs-axios, I successfully transferred client-side data to the server-side using Java with SparkJAVA Framework to manage the request-response cycle. The following code snippets demonstrate how Form-Data is posted from vuejs to java. const formData ...

Encountering "npm WARN optional dep failed, proceeding with fsevents" error while attempting to install vue-cli on AWS/EC2 instance

I'm in the process of setting up vue-cli on AWS. Everything seems good with my permissions, and I have node v4.4.5 installed. Upon executing npm install --global vue-cli, the cursor flashes for approximately 30 seconds before displaying this error m ...

In what ways can I align the ESLint rules of my Node.js server with those of my Vue.js frontend?

I am looking to ensure that my Node.js server-side files follow the same ESLint rules as my Vue.js frontend. The .eslintrc.js file in my Vue project is structured as follows: module.exports = { root: true, env: { node: true }, extends: ["plugin ...

I am unable to execute npm run dev

I attempted to replicate my friend's project from Git, but encountered an issue: Vite manifest not found at: D:\laravel\PBL-Kelompok-5-2\public\build/manifest.json Start the development server Run npm run dev in your terminal and ...

What sets npm run watch apart from npm run hot in Laravel?

Since both of these commands are supported in Laravel, I'm a bit confused about their distinctions. However, I did observe that npm run hot does not update when I make changes to scss files, whereas npm run watch functions correctly. ...

When setting up Vue.js for unit testing, the default installation may show a message stating that

Recently set up a fresh Vue project on Windows 7 using the VueJS UI utility. Unit testing with Jest enabled and added babel to the mix. However, when running "npm test" in the command line, an error is returned stating 'Error: no test specified' ...

Utilizing Vue.js to connect with a Node.js server

After setting up a basic Node.js server, the following code is running successfully: var http = require('http'); var server = http.createServer(); server.on('request', function(req, res) { res.writeHead(200, { 'content ...

The functionality of Highcharts-more.js is not functioning properly within a project set up using vue-cli

Recently, I have been working on a vue-cli project and attempting to create a polar chart similar to the one shown here: To achieve this, I needed to install and import the highcharts and highchart-more libraries using npm. However, upon importing both fi ...