The computed value failing to refresh

I'm facing an interesting issue. I am currently developing a simple time tracking application.

Here is the form I have created:

<form class="form" @submit.prevent="saveHours">
    <div class="status">
        <div class="selector" v-for="(select, index) in select_all">
            <component :is="select" :id="index" @percentage="trackTime"></component>
        </div>
    </div><!-- /.status -->
    <div class="form-submit">
        <button type="submit" class="form__submit">
            <span v-if="loading">Guardando...</span>
            <span v-else>Guardar</span>
        </button>
    </div>
</form>

Next, you can find my Vue code snippet below:

export default {
    name: 'home',
    data() {
        return {
            select_all: [Selector],
            loading: false,
            allTimes: [],
            saveForm: []
        }
    },
    components: {
        Selector
    },
    computed: {
        calculateTotal() {
            return this.allTimes.reduce((accumulator, currentValue) => parseInt(accumulator) + parseInt(currentValue), 0);
        }
    },
    methods: {
        addNewSelector() {
            this.calcTotal();
            this.select_all.push(Selector)
        },
        trackTime(time, index, proyecto) {
            this.currentTime = time;
            this.allTimes[index] = time;

            const data = {
                time,
                proyecto
            }

            this.saveForm[index] = data;
        },
        saveHours() {
            const currentWeek = moment(new Date()).format('w');
            const diverRef = db.collection('divers').doc(firebaseAuth.currentUser.email);
            const currentWeekRef = diverRef.collection('reportes').doc(`semana_${currentWeek}`);
            var self = this;
            currentWeekRef.get().then(function(doc) {
                if ( doc.exists ) {
                    console.log('Ya registraste tus horas');
                } else {
                    currentWeekRef.set({
                        data: self.saveForm
                    })
                }
            });
        },
    }
}

I've implemented a component called , where I emit the time entered by the user back to the parent and utilize the trackTime function to add each project's time to the allTimes array.

I'm attempting to use a computed property named calculateTotal to sum up the times so I can track when a user has completed 100% of their scheduled hours. However, it seems like the total isn't updating as expected.

This situation is quite perplexing. While using the computed property as a method works perfectly fine, it doesn't update dynamically while the user is inputting values. Since I've employed a component for the input field, I cannot rely on keyup events.

I've been grappling with this challenge for quite some time now without any breakthroughs. Any insights are highly appreciated! Thanks!

Answer №1

If anyone else is facing the identical issue, Sergeon and Roy J were correct in their suggestions.

While troubleshooting, I came across this snippet of code:

this.allTimes[index] = time;

This line was causing issues with Vue. To resolve the issue, I modified the code to:

this.allTimes.splice(index, 1, time)

After making this change, everything now works perfectly fine.

Thank you!

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

Encountered an error: "switch/mergeAll/flatten is not a valid function" when working with the http driver

As I delve into learning CycleJS, one thing that has caught my attention is the usage of Cycle's HTTP Driver. It seems that in order to reach the stream level, merging the response stream stream with RxJS switch/mergeAll is essential. However, when at ...

Looking for a way to update a world map image by selecting multiple checkboxes to apply a flood fill color to different countries using Mogrify

Exploring different methods to achieve my goal, I am wondering if creating a web service where users can track visited countries on a world map can be done in a simpler way than using Javascript or Ajax. The idea is for users to mark the countries they hav ...

Is there a way to enable code completion for Firebase on VS Code?

After successfully setting up Typescript for code completion following the guidelines provided in this resource, I now want to enable code completion for Firebase in VS Code. However, I am unsure of the steps to achieve this. How can I activate code compl ...

Setting an interval for a specific function to trigger after a delay of 5 seconds

I'm struggling with setting an interval for the $.get ajax method in my code. Take a look at what I have so far... setInterval(function () { passFunction(jsonData); } ,5); $.get({ url: 'pass.php', success: ...

What steps can I take to deactivate input and stop it from being accessible on the browser?

insert image description Is there a method to block users from accessing disabled input fields in the browser? Any recommendations or solutions would be greatly appreciated. Vuejs is utilized within my project. Implementing this feature serves as a secu ...

Add a click event to elements that match

I must admit that I am not particularly knowledgeable in Javascript/jQuery and my question might come across as trivial. However, I am trying to assign a click event to every element on the page with the following code: $(document).ready(function () { ...

Setting the cache to false during an httpget request in an mvc4 controller action: tips and tricks

My httpget request to a controller action looks like this: $.get('/Course/ExplanationCorrect/', postData, function (data) { $('#SurveyDiv').html(data); }); While it works on all other browsers, I'm facing an issue with IE10 o ...

How can we customize HTML images without allowing third-party JavaScript to enlarge them?

I am using Blogger to host my website and I have a basic knowledge of HTML and CSS. I want to incorporate a collaborative add-your-link feature using SimplyLinked. However... They provided me with the following HTML: <script type="text/javascript" src ...

What is the best way to translate my Vue components library for different languages?

Creating my own Vue components library has been rewarding, but I face the challenge of localizing a lot of text within these components. The usual translation tool, vue-i18n, requires being attached to Vue (e.g. Vue.use(VueI18n)), which can create conflict ...

Ways to minimize renders while toggling a checkbox

I'm currently working on developing a high-performance checkbox tree component. To manage the checked checkboxes, I am utilizing a parent level state that contains an array of selected checkbox IDs => const [selected, setSelected] = useState([]); ...

Can we not customize a nested component using the 'styled()' function in MUI?

Looking at the code snippet below, my attempt to style an MUI Stack component within an MUI Dialog component seems to be falling short. The Stack styles are not being applied as expected: const CustomDialog = styled(Dialog)(({ theme }) => ({ ' ...

Unable to interpret data from JSON file

I have written the following code to read a JSON file. It is not throwing any errors, but I am receiving a null value in the variable: var myData = null; $.ajax({ type: 'GET', async: false, url: 'myJson.json', dataType: ...

Tips for securing apiKey and apiPass in Shopify using VueJs

Implementing Shopify's admin API in VueJs to handle some Api calls. However, I am concerned about the security of sending the Key and Password as it appears they are exposed on my site. How can I ensure their protection? Or perhaps I have set it up in ...

Store and Persist Data for a Model in MongoDB

Currently working through the MongoDB and Mongoose section on FreeCodeCamp. The challenge involves creating a document instance using the Person constructor previously built. The object passed to the constructor should have fields for name, age, and favor ...

Displaying data on View is not working after navigation

I'm facing an issue where the data is not displaying on the view after routing, even though it appears in the console. Surprisingly, if I don't change the view, the data shows up. Additionally, if I call the service directly from the view, I can ...

Executing the main process function

One of the challenges I'm facing is calling a function from the main process in Javascript while a button is clicked in another file. Here is the code snippet: Main.js const electron = require( 'electron') const {app, BrowserWindow} = elec ...

Error encountered when attempting to perform a Fetch POST request with same-origin credentials (Express & React)

I'm currently testing a login process in React that reaches an Express API route; the HTTP request is a POST made using fetch as shown below: const response = await fetch(`http://localhost:3001/login`, { method: "POST", mode: "same- ...

Simple steps for Mocking an API call (Get Todos) using ComponentDidMount in React with Typescript, Jest, and Enzyme

About the application This application serves as a basic To Do List. It retrieves tasks from an API located at https://jsonplaceholder.typicode.com/todos?&_limit=5. Objective of the project The main goal is to test an API call that triggers ...

Ensuring that EJS IF/ELSE statements are evaluated accurately

I am encountering an issue where my variable 'answer' is returning the string 'success' and displaying correctly in the view. However, the IF/ELSE statement always seems to evaluate to the ELSE condition and displays 'no' inst ...

Accessing form data within Mongoose schema hooks via JavaScript

I have a form where I've split the content into two separate MongoDB schemas. I want to access variables that are within node.js/express.js directly in mongoose schema hooks, whether through pre or post hooks of the schema. Here are my files: expres ...