Vue removes existing data values post @selection change in the select box

I am facing an issue with my code where the data property in Vue.js appends the current result to the previous one instead of replacing it when a new option is selected from the select tag. I want the current data to be deleted and replaced with the newly selected result each time.

Shown below is the graph:

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

When I click on Vince from the select box, I receive the correct data and display on the graph as well. Here are the details from Vue devtools:

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

However, when I click on Mark, a teacher for which there is no data available, the previous array's data remains intact. Even after clicking back on Vince, the old data persists. The following results and graph show this scenario:

https://i.sstatic.net/jns3O.png https://i.sstatic.net/SOxXe.png https://i.sstatic.net/3Rz8x.png

The current code that I have tried is not working as expected. Below is the snippet of the code:

   getdata() {
                    let self = this
                    axios.get('/getGraph/' + self.teacher)
                        .then(({
                            data
                        }) => {
                            if(data.length > 0){
                                data.splice()
                            }
                            else{
                                data.date.forEach(x => {
                                    self.dataSource.data.push(x);
                                });
                            }
                        })
                }

Here is my original code for reference:

     getdata() {
                    let self = this
                    axios.get('/getGraph/' + self.teacher)
                        .then(({
                            data
                        }) => {
                            data.date.forEach(x => {
                                self.dataSource.data.push(x);
                            });
                        })
                },
                getTeachers() {
                    axios.get('getTeachers')
                        .then((res) => {
                            this.teachers = res.data
                        })
                        .catch((e) => {
                            console.log(e)
                        })
                }

I would greatly appreciate any insights on what might be wrong with my code and how I can achieve the desired functionality. Thank you!

Answer №1

It is important to clear your data every time you receive new data from the server, as shown in this example.

 axios.get('/getGraph/' + self.teacher)
        then(({
                            data
        }) => {
        self.dataSource.data = []
        data.date.forEach(x => {
            self.dataSource.data.push(x);
        });
 }) 

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

What is the mechanism behind JSON.parse()?

As I delve into the realm of using JavaScript to parse an object retrieved from a PHP file, a snippet of pertinent code catches my attention: var name = document.getElementBId("name").value; var XHR = new XMLHttpRequest(); XHR.open("GET', 'looku ...

Removing an unnecessary DIV element from an HTML Document

I have been working on a News application and am utilizing a web product to fetch News Headlines. When I request a NewsHeadline, the product sends back an HTML Code containing the News Headline. <div class="mydiv"> <script type="text/javascript ...

Using PHP, we can easily create an array and store values that are stored in variables

Hey, I currently have 2 variables set up. $firstVariable = "123"; $secondVariable = "321"; Both of these variables are dynamically calculated and subject to change based on varying circumstances. Now, I am looking to combine these values into a single ar ...

Utilizing JQuery's .Toggle function in conjunction with a stylish CSS transform button

I am trying to create a toggle menu that shows and hides itself without requiring the button to be clicked twice. I have added e.preventDefault(); which solves the issue, but now the button does not transform as intended. $(document).ready(function() { ...

Showing Real-Time Information in the Render Function

Looking for some guidance on how to create a dynamic Card using data from an API. I'm able to retrieve the data successfully, but I'm having trouble displaying it in the render method. Here's a snippet of my component where I use axios to f ...

Attempting to seamlessly run a PHP file in the background by utilizing Ajax when a link is clicked

I am trying to execute a PHP file in the background when a link is clicked without the user being directed to the actual PHP file. After realizing that Ajax is the only way to achieve this, I attempted to implement it but encountered issues. Instead of ru ...

Locate the parent element that has the smallest amount of space taken up by its child elements

My goal is to determine which container, among several <divs>, each containing multiple child <divs> of varying sizes, has the smallest amount of space covered by the child elements. <div class="container" id="first"> ...

Diminishing of the darkness

Imagine a tree adorned with beautiful alpha leaf textures. The intricate pattern of the falling shadow casts a deep darkness on the leaves "below", causing the entire model to appear dark. https://i.sstatic.net/N5ocS.png https://i.sstatic.net/EL5BZ.png ...

Ways to restrict express API requests based on pricing tiers

I am currently developing a public API that includes a pricing plan for client accounts. I need to set limits on API requests based on each account's plan. My stack includes NodeJS and ExpressJS. Unfortunately, there seems to be an issue with the cod ...

Conceal the slider thumb within the material-ui framework

I've been attempting to conceal the slide thumb, initially without using a library. However, I started considering utilizing material-ui as it might make the process easier. Hence, I'm seeking assistance here. Below is my code snippet: import * ...

Switching the visibility of multiple textareas from block to none

I am currently exploring ways to make one text area disappear while another one appears in its place. With limited knowledge of Javascript and just starting my journey into HTML and CSS, I am reaching out to the forum for assistance or guidance on the rig ...

Tips on setting default values for the Date Type in Vue, Express, and Mongo / Mongoose

I am currently working on a project that involves using VueJS, ExpressJS, and MongoDB for CRUD operations. In my schema definition in Mongoose, I have set a deadline field with the type of Date and made it optional. However, when I do not send a deadline ...

Setting up a variable within a v-for iteration in Vue JS

I'm currently facing a challenge in finding a solution to what appears to be a simple problem. Within a template, I am using a v-for loop to generate some content. In this content, I need to execute a function to check if the contentID matches an ID ...

Error in executing a function within an asynchronous function sequence

Whenever a user logs in, I want to update their data in Firestore. However, the code I am using does not seem to work as expected. It fails to create a custom User object from the firebase.User. Can anyone help me understand why this is happening and how ...

Is it possible to alter the default component directory location in VuePress to '.vuepress/components' using the register-components feature?

Attempting to incorporate a custom directory of components into vuepress using the plugin register/components has proven to be challenging. My setup looked like this: module.exports = { title: 'Hello VuePress', description: 'Just playi ...

What could be the reason behind the absence of this.props.onLayout in my React Native component?

In my React Native app, I have the below class implemented with Typescript: class Component1 extends React.Component<IntroProps, {}> { constructor(props){ super(props) console.log(props.onLayout) } ... } The documentation for the View ...

When utilizing AngularJS, a parse error is triggered by array[ {{value}} ], but I prefer to overlook it

Within the controller, I have a selection list that is displayed like this: <select class="input form-control" id="animationTime" ng-options="item as item.label for item in aniCon.timeOptions track by item.id" ng-model="aniCon.popupTime" ...

Sending query parameters from one URL to another using jQuery

Greetings! I have implemented a load more feature using a script that loads additional content on the same page when the 'Load More' button is clicked. Below is the script: <script type="text/javascript"> var track_page = 1; load_c ...

Combining ApolloProvider and StatsigProvider in ReactJs: A Step-by-Step Guide

Currently in my React (Next.js) application, I am utilizing statsig-react to switch between mastergraphql endpoint URLs. However, I am encountering an issue when trying to connect statsig with Apollo. This is how my app.js file looks like: const apollo = ...

What is the reason for Rich file manager to include filemanager.config.json instead of simply adding an image to the text

I have integrated Rich File Manager with Laravel 5.3.20 using the default configuration provided below: Javascript <script> CKEDITOR.replace( 'textarea', { filebrowserBrowseUrl: '{!! url('gallery/index.html& ...