Vue.js state not updating issue solved

Issue Resolved

I encountered a problem with a VueJS component that is supposed to load and display a list of services from the backend in a table. Despite successfully fetching data from the API, the table remained empty. This component is integrated with Laravel.

The VueJS Component I'm referring to is ResourceTable.vue:

<template>
  <div>
    <a class="button" v-on:click.native.prevent="services">Load</a>
    <b-table :data="items" :columns="columns"></b-table>
    {{items}}
    <br>
    {{ done }}
  </div>
</template>


<script>
    export default {
        name: 'resource-table',
        props: ['resource'],
        data() {
            return {
                loading: false,
                done: 'loading',
                items: [],
                columns: [{
                    field: 'name',
                    label: 'Name'
                }],
                host: 'http://services.local/api/v1'
            }
        },
        methods: {
            /*
             * Load async data
             */
            services: function() {
                console.log('loading data');
            this.loading = false;
            // const vm = this;
            axios.get(`${this.host}/${this.resource}`)
                .then(({ data }) => {
                this.items = data.data;
                console.log(this.items)
                this.loading = false;
                this.done = 'loaded';
                this.$toast.open('Data load complete')
                })
            }
        },
        mounted() {
            this.services()
        }
    }
</script>

<style scoped>

</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<resource-table resource="workspaces"></resource-table>

Although the API was functioning properly and returning data from the server, the table was not reflecting the updated information.

If I manually added values to the items array, they appeared in the table. However, the data retrieved from the API did not populate the table as expected.

Issue Resolved

The root cause was identified as a duplicate inclusion of a JavaScript file. Removing one instance solved the issue. Thank you to everyone who helped troubleshoot.

Answer №1

Although I am not familiar with Laravel, it seems like the issue lies in this particular code snippet:

this.items = data.data;

To ensure that the data in the 'items' is reactive, you should populate it using a loop. Here's an example of how you can achieve this (utilizing either a for loop or forEach):

this.items.splice(0); // To clear existing data if needed

for (let i = 0, l = data.data.length; i < l; i++) {
  this.items.push(data.data[i]);
}

I haven't reviewed the entire code, but this should give you a general understanding;

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

Include parameters for a pagination system

I have a script that fetches data from my database and generates pagination. Everything is working fine, but now I want to include a conditional statement to differentiate the user level as New, Current, or Renewing client. I've already set up some s ...

Altering the background hue of a div with jQuery based on its existing color

As someone new to jQuery, I have been delving into its intricacies and experimenting with it as much as possible. However, I am facing a time crunch and need to complete this project quickly. My question revolves around a particular issue... I have a link ...

The 404 Page Not Found error is displayed when an Angular JS Encoded URL

I have successfully developed an AngularJS application. The application functions properly with the URL provided below: http://localhost/AngularDemo/about However, when I try to modify the URL as shown below, it redirects me to a 404 error page: http:/ ...

Transforming an SQL Query into JSON format using Oracle 11g in Oracle Application Express (APEX)

In my Oracle APEX v4.2 project, I am dealing with a sizable table containing about 40 columns and up to 50 rows. My goal is to use SQL to fetch the data from this table and convert each row into a JSON object. Operating on Oracle 11gR2, I require this JSO ...

Utilize emit to distribute / allocate a variable

I have some variables stored in a file called server.js (and they tend to change frequently). My goal is to pass these variables to client.js whenever the client sends a request (triggers the 'validate' event). Even though the event is triggered, ...

Exploring the new features of FabricJS version 3.4.0: Enhancing performance with filters and understanding the limitations of maxTexture

Introduction: I have been experimenting with fabricJS image filtering features to incorporate them into my web application, but I have encountered the following issue. It appears that fabricJS default sets the image size cap (textureSize) on filters at 2 ...

Having trouble with deploying a Vuejs app from git on Jelastic

This is my first experience with Jelastic and I am attempting to deploy a Vue.js app from Git. After creating a Node.js environment and deploying my Vue.js app, I followed these steps: cd ROOT npm install npm run build I received a successful message th ...

Identifying the opening of a folder or file in an electron/node application

Is there a way to retrieve the name of a folder or file when they are opened? I have tried using fs.watch event, but it only seems to work when renaming, adding, or removing files/folders within the specified directory. For instance: //This code only de ...

What could be the reason for the array not being sorted correctly in ReactJS, even when it is already sorted by the backend system

I am working with an array that is structured like this: const chapters= [ { index:1, title:'chapter-1', lessons:[] } { index:2, title:'chapter-2', lessons:[] } { index:3, title:'chapter-3', lessons:[] } ] The ar ...

Difficulty arises when attempting to employ JSON.parse() on an array encoded utilizing PHP's json_encode() function

My Vue component retrieves data from Apache Solr, where the field I'm working with is an array generated using json_encode() in PHP. Here's my component method: data () { return { slideshow: {}, slides: {} } } ...

Using jQuery within an Angular Controller: The specific function $(...).overhang is not recognized in this context

Recently, I decided to integrate overhang.js into my application because of its appealing alert messages. Initially, it seemed like a simple task... All I needed to do (or so I thought) was replace the line in my controller, alert("An HTTP request has be ...

An error occurred when attempting to search for 'length' using the 'in' operator in the context of the Datatables plugin and jQuery 1.11.3

I implemented the jQuery Datatables plugin in my tables for pagination, sorting, and searching functionalities. However, I am facing issues where the elements are not working properly, and the pagination occasionally fails to display. The Chrome console is ...

"Experience random updates in the priv/static/js/app.js file whenever changes are made to Vue files in the Phoenix/Elixir/V

I have a vue.js/Phoenix application and I am currently facing a challenge with configuring the frontend assets properly. I have noticed that my priv/static/js/app.js file keeps updating whenever I make changes in other files, and I am unable to understand ...

Adjust CRM 2011 settings to allow bulk editing exclusively for specific entities

Currently, my goal is to restrict bulk editing for most entities except for the "Campaign Response" entity. To accomplish this task, I have taken the following steps: Disabled the Out of the Box (OOTB) edit button globally (due to restrictions on editin ...

What is the best way to access the entire pinia state object?

I'm looking to create a getter in my pinia store that returns all state properties. export const useFilterStore = defineStore('filterStore', { state : () : FilterState => ({ variables:[] as string[], categories:[] as s ...

Issue with retrieving element ID (Uncaught TypeError: Unable to assign value to property 'innerHTML' of null)

I am experiencing an issue where I am unable to get a value from a div and send it to the database. It was working fine on my localhost, but after uploading the source code to my host, it has stopped functioning properly. Upon inspecting the console, I en ...

What are the disadvantages associated with the different methods of submitting data?

My goal is to create an Online testing platform. I have come across two different approaches to verify user-selected answers. Approach 1 <div class="qContainer" index="0"> Who holds the record for scoring 100 centuries in International cricke ...

Retrieving HTML content from Wikipedia's API using JavaScript

I am encountering an issue where every time I attempt to log data to my console, an error occurs. Could someone kindly point out what may be the problem with the code? My objective is to actually showcase the html content on a webpage. Below is the code ...

Setting the CSS position to fixed for a dynamically generated canvas using JavaScript

My goal is to fix the position style of the canvas using JavaScript in order to eliminate scroll bars. Interestingly, I can easily change the style using Chrome Inspector with no issues, but when it comes to implementing it through JS, I face difficulties. ...

Creating expandable card components with React and CSS using accordion functionality

I am currently working on creating a card that will expand its blue footer when the "view details" link is clicked to show lorem text. However, I am encountering an issue where the blue bottom of the card does not expand along with the lorem text. You can ...