Problem with synchronized real-time list when fetching data from server in VueJs

My website has a dynamic list feature where users can input text to create new projects. The program sends an HTTP request when the page is loaded for the first time to retrieve all projects for the current user and display them on the screen. Users can also add new projects, but they are not immediately shown on the page without refreshing.

The JavaScript code for this functionality is:

    export default {
      name: "Projects",
      data: function() {
          return {
            Projects: [],
            ProjectName:'',
            Username:''
          }
      },
      created(){
        this.GetAllProjects(); 
      },
      methods: {

        CreateNewProject: function() {

          var app = this; var idNo = XXXXX; var username= XXXXX;

          axios({
            method: "post",
            timeout: 3000,
            headers: {
                               .......
            },
            url: "XXXXXXX", data: {
              name: app.ProjectName,
              username: username,
            }
          }) 
          .then(function(response) {
            console.log(response);
            app.ProjectName = "";

          })
          .catch(function(error) {
            console.log(error);
          });
        },
        GetAllProjects: function(){

          var app = this; app.id = XXXX; app.Username= XXXX;

          const instance = axios.create({
            timeout: 3000,
            headers: {
                           ......
            }
          });
          instance.get("XXXXX")
            .then( function(response) {
              console.log(response);

              Object.keys(response.data.result).forEach( function (product) {
                console.log(response.data.result[product]);
                console.log('product number: ' + product);

                var subscribersCounter = 0;

                let example = {
                  name: response.data.result[product].name,
                  id: response.data.result[product].id,
                  subscribers: response.data.result[product].subscribers,
                  products: response.data.result[product].products,
                };

                let uploadedExample = {
                  name: '',
                  id: '',
                  subscribers: '',
                  products: {name:'',color:''},
                };

                uploadedExample.name = example.name;
                uploadedExample.id = example.id;

                if ( example.subscribers ) {
                  Object.keys(example.subscribers).forEach(function (key) {
                    subscribersCounter++;
                  });
                }

                uploadedExample.subscribers = subscribersCounter;

                if ( example.products ) {
                  Object.keys(example.products).forEach(function (Pkeys) {
                    uploadedExample.products.name = Pkeys;
                    Object.keys(example.products[Pkeys]).forEach(function (key) {
                      if (key == 'color') {
                        uploadedExample.products.color = example.products[Pkeys][key];
                      }
                    });
                  });
                }

                app.Projects.push(uploadedExample);

              });

            })
            .catch(function(error) {
              console.log(error);
            });


        }
      }
    }

In the template section:

<b-col v-for="(project,index) in Projects" :key="index">
            <b-row><h1> {{project.name}} </h1></b-row>
..........

Solution Attempted:

While the initial load correctly fetches and displays all projects for the user, adding a new project does not update the list on the screen dynamically. Refreshing the page with location.reload(); was attempted but did not provide the desired outcome.

Note: Simply updating the array of projects will not suffice as I require the additional data obtained from the HTTP request for processing purposes.

Answer №1

After creating a new project, don't expect your list of existing projects to automatically update. You'll need to manually add the new project to the list once the request is successful or refresh the entire list by fetching all projects again (the same as when the page initially loaded). Avoid hard-refreshing the page using location.reload().

The HTTP API should respond with a project object when creating a new project. This object can then be transformed as needed for the frontend and appended to the array.

Make sure not to duplicate any data processing code between operations for "get all projects" and "new project."

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

Using Angular JS to manage multiple views with a single controller

Would it be considered best practice to use one controller, yet have two distinct HTML file templates that present the same data in different formats? Essentially, I require a slightly altered template for displaying content in a modal dialog and another ...

Vanilla.js with Vue does not support the onclick event functionality

Currently, I am facing the need to utilize vanilla.js in my application due to the presence of html entities retrieved from the database that require special treatment. Since the babel compilation process has already concluded, I am resorting to manipula ...

The nodemailer module in Node.js encountered an issue while trying to send an email, resulting

Looking to confirm registration, I want to send an email from my server (kimsufi). To accomplish this, I am utilizing nodemailer which can be found at https://github.com/andris9/Nodemailer Encountering the following error: Error occurred Sendmail exited ...

Maintaining a security token across multiple requests

A prototype application is being developed with the following features: An HTML website integrated with knockoutjs Communication with Web API services using jQuery/Ajax The goal is to restrict access to services only to authorized users. Security measur ...

Transmitting information from directive to parent scope controller

I've successfully implemented a directive that generates a Google map on the page. Now, my goal is to pass the map object back out of the directive and into the parent controller. This will allow me to utilize it in various methods as needed. While ...

JavaScript example: Defining a variable using bitwise OR operator for encoding purposes

Today I came across some JavaScript code that involves bitwise operations, but my knowledge on the topic is limited. Despite searching online for explanations, I'm still unable to grasp the concept. Can someone provide insight into the following code ...

Mongoose: Enhancing Arrays with maximum values for each item

How to Update an Array Property in Mongoose with Item-Wise Max and Default Null Upon Instantiation I have a MongoDB collection that stores time series data in a fixed-length array (1 item per minute, 1 document per day). { 'series': '#1& ...

Error in height calculation due to setting the CSS property line-height

I am facing a challenge in setting the height of a parent ul element based on the included li's. The issue arises when the CSS property line-height contains fractional digits, causing inaccuracies in the calculation. This results in the calculated hei ...

Encountering an issue while attempting to implement Redux Toolkit alongside the MUI ToggleButtonGroup component

The error message initially started as: Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. When I attempted to update the Redux state using a dispatcher, the handleChange function suddenly showed an e ...

Creating powerful Vue event handlers with composable functions

I am currently working with Vue 2.0, ES6, and Webpack. In my project, I have a Parent component and several child components called text-input. Each text-input emits a change event that should modify a different property inside the Parent component. For i ...

Is it possible to view the object sent from AJAX to PHP in PHP using a debugger?

I'm facing an issue where I am making an AJAX call to a PHP file, sending a JSON object as a parameter from JavaScript. The PHP file is supposed to perform some logic with the object and return it using json_encode('whatever');. However, the ...

Using jQuery to retrieve the values of two distinct sliders and executing a specific mathematical operation

I have two sliders with their own values and properties: https://i.stack.imgur.com/3OZqr.gif My goal is to retrieve the values of these two sliders and calculate a result that will be displayed next to the interest label. The calculation formula is: poun ...

How can I detect the scroll action on a Select2 dropdown?

Is there a way to capture the scrolling event for an HTML element that is using Select2? I need to be able to dynamically add options to my dropdown when it scrolls. Just so you know: I am using jQuery, and the dropdown is implemented with Select2. The ...

Triggering a function without the presence of an actual event

I need to come up with a solution for reusing a function triggered by an event binding. This problem stems from browsers remembering checkbox states, which is why I have to call the function on document load. One approach could involve wrapping setGrid() ...

Simulating a JavaScript constructor using Sinon.JS

I need to write unit tests for the ES6 class below: // service.js const InternalService = require('internal-service'); class Service { constructor(args) { this.internalService = new InternalService(args); } getData(args) { let ...

I am sometimes experiencing issues with activating ajax code using Bootstrap 3 modal

I'm stumped trying to find a solution for this issue. Currently, I am utilizing the bootstrap modal to retrieve ajax content from a specified URL. To prevent content overlap, I am using $.removeData() when reloading the content. The problem arises w ...

"Creating mobile apps with Cordova using Vue framework, running on Android Virtual

After following a tutorial, I successfully created my own Android Cordova app using this plugin: https://www.npmjs.com/package/vue-cli-plugin-cordova I stored all the images for my app in the public folder. The structure of my project folder is as follows ...

'Sys is not defined' JavaScript error

I've exhausted all my efforts searching for a solution online, but I'm still struggling to find an answer. I am facing a challenge with several projects that were initially developed for .Net 2.0 and hosted on IIS6 Server 2003 32 bit. Now, as pa ...

The contenteditable div's selectAll feature doesn't function properly when it gains focus

I'm working with divs in a table structure and here's an example: <div contenteditable="true" onfocus="document.execCommand('selectAll',false,null)">Something</div> Clicking on a div to focus works perfectly, selectin ...

Gathering feedback from a webpage using JavaScript and jQuery

I have been experimenting with different tools such as Selenium and BeautifulSoup in an attempt to scrape the contents of the following website/pages: . Specifically, I am looking to extract the reviews/sections which are dynamically loaded by JS, jQuery ...