VueJS component experiencing stagnant DOM updates

I have reviewed similar posts on "DOM not updating", but have yet to find a solution. I am working on a task app and it can successfully load, add, and delete tasks from Firestore. However, I'm facing two issues and would like to address the first one. Even though the Vuex store array is updated correctly when adding or deleting data, the DOM does not update dynamically. It only reflects the changes upon page reload.

I've shared the code for both the component and the store below. While I believe I'm looking in the right direction, I suspect there might be something I'm missing.

Thank you in advance

Store code:

import Vue from 'vue'
import Vuex from 'vuex'
// import firebase from 'firebase'
import router from '@/router'
import db from '@/db'
import firebase from '@/firebase'

Vue.use(Vuex)

export const store = new Vuex.Store({
  state: {
    // State object properties
  },
  mutations: {
    // Mutations methods
  },
  actions: {
    // Actions methods
  },
  getters: {
    // Getters methods
  }
})

This is the component (Vue app -> Home -> Grid -> Tasklist (this):

<template>

  <!-- Component template -->
  
</template>

<script>

export default {
  data () {
    return {
      // Data properties
    }
  },
  props: ['Id', 'title'],
  computed: {
    // Computed properties
  },
  methods: {
    // Methods
  }
}

</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.container {
  max-width: 1200px;
}
</style>

Answer №1

There is no mutation in place to directly modify your tasks array. For instance, the code this.state.tasks.pop(payload) is executed in the deleteTask action rather than the mutation.

The only way to change the state in a Vuex store is by committing a mutation. https://vuex.vuejs.org/guide/mutations.html

This explains why you see the correct result after reloading: The Firestore functions correctly and updates its values. It reflects the new and updated tasks array only after reloading, but Vue's display of the tasks array remains unchanged before reloading due to the Vuex state not being altered.

A simple solution to this issue:

Create a new mutation:

REMOVE_FROM_TASKS (state, payload) {
    // Algorithm to remove, for example, by ID
    state.tasks = state.tasks.filter(e => {
        return e.id !== payload;
    });
},

Utilize this mutation in your action:

deleteTask ({ commit }, payload) {
  db.collection('tasks').doc(payload).delete().then(() => {
    commit('REMOVE_FROM_TASKS', payload)
    commit('deletedTask', true)
    commit('loadedTasks', true)
  }).catch(function (error) {
    console.error('Error removing document: ', error)
    commit('deletedTask', false)
  })
}

Answer №2

By making some adjustments to the component structure, the DOM now properly updates when items are deleted. The new hierarchy is as follows: Vue app -> Home -> Grid -> Tasklist -> TaskListItem. However, an issue still persists where adding multiple entries with different titles results in them being displayed identically on the DOM until a complete reload is done.

Refer to the code snippet below:

Store:

import Vue from 'vue'
import Vuex from 'vuex'
// import firebase from 'firebase'
import router from '@/router'
import db from '@/db'
import firebase from '@/firebase'

Vue.use(Vuex)

export const store = new Vuex.Store({
  state: {
    // State properties
  },
  mutations: {
    // Mutations for changing data in the store
  },
  actions: {
    // Actions for changing data in the store
  },
  getters: {
    // Getters to receive data from the store
  }
})

TaskList:

<template>

  <!-- TaskList template code -->

</template>

<script>

// TaskList component script

</script>

<style scoped>
  // Scoped styles for the TaskList component
</style>

TaskListItem:

<template>
  // TaskListItem template code
</template>

<script>:

// TaskListItem component script

</script>

<style scoped>
  // Scoped styles for the TaskListItem component
</style>

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 reason for recursion not producing a new object as output?

Trying to filter out nodes in a recursion function that iterates through a tree based on the registry property. function reduceNodesRegistry(source: any) { if (!source.registry) return source; return { ...source, children: s ...

Refreshing the webpage causes a change in the displayed HTML content

Upon the initial load of the HTML, the text will show as "Yes". However, upon reloading or when loading from the cache for the second time, it should display a different text, "NO". ...

Using JavaScript to place image data on the canvas in an overlay fashion

I recently wrote the code below to generate a rectangle on a canvas: <!DOCTYPE html> <html> <body> <canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;"> Your browser does not support the HTML5 canv ...

What is the best way to trigger a particular function only when a Vue component is called by a specific component, and not by any other components?

I've created a component called select-diagnosis that is utilized by various components. When select-diagnosis is invoked by a specific component known as PtdTreatment, it should execute a particular function within the fetchDiagnosis function. Howev ...

Tips for maintaining the visibility of the dynamic submenu while hovering over either the parent menu or submenu in vuejs

I'm currently working on a dynamic sidebar in vuejs and I need some assistance. The issue I'm facing is that I want the submenu to remain open when hovering over either the parent menu or the submenu itself. However, when I move the mouse away fr ...

Guide on adding a personalized table or Div section in a datatable

I am looking to add a custom table above a datatable, specifically I want the custom table to be displayed above the header columns. Here is the code I have tried: columns: [ { "data": "WorkFlowType" }, { "data": "WorkflowInstanceId" } ...

Unable to assign headers once they have already been sent to the recipient - a Node.js error

Encountering an error message stating "Cannot set headers after they are sent to the client." I've researched and it seems like multiple callbacks may be causing this issue. However, I'm struggling to find a solution. Any assistance in resolving ...

Having trouble with Vue/Nuxt page transitions not working correctly during the leave phase

My attempt at implementing page transitions using CSS didn't quite work, especially the leave transition. So, I turned to using JS Hooks instead, but unfortunately, the leave animations still refuse to cooperate. After meticulous troubleshooting and c ...

What is the proper way to incorporate a backend variable within an EJS script block?

<!-- begin snippet: js hide: false console: true babel: false --> <script> // initializing the map var map = L.map('map').setView([25.037393872113785, 121.56372070312499], 12); // loading a tile layer var baseLayer = L ...

Unable to get Discord.js sample code functioning correctly

Despite my best efforts, I can't seem to figure out why this simple example code is not working. As a newcomer to Java Script, I am struggling with understanding why the line GatewayIntentBits.Guilds is causing an error. Surprisingly, when I comment o ...

Error message "Undefined is not a function" occurred while using jQuery's .replace and scrollTop functions

I'm having issues with the scroll function in my code. It doesn't seem to be able to locate the ids in my HTML, even though I can't figure out why. I had a previous version that worked perfectly fine (unfortunately, I didn't save it D:) ...

Javascript and the Cookie Conundrum

My goal is to use Javascript to create a cookie that stores the value of an input field with the id "username" every time a button is pressed. Then, I want to retrieve and display that cookie value on the website. I attempted to implement this myself to te ...

Is it possible to substitute a one-line jQuery.load() with a fetch() function that achieves the same result?

I am currently working on a page where I utilize a single line of jQuery code: $('#id').load('/url'); This line allows me to load a fragment into a specific place in the DOM. However, I am now considering reducing my reliance on jQuer ...

Utilizing the swiper's onSlide change event to access various methods of my component

I am attempting to update another component in my application whenever the user changes the slide on the swiper. I have succeeded in console logging the swipe and identifying the slide number, but when I try to call the other method to render the other com ...

Choose a file in React by specifying its path instead of manually picking a file

Is there a way for me to automatically select a file from a specified path into my state variable without having to open a select file dialog? I'm looking for a solution where I can bypass the manual selection process. Any suggestions on how this can ...

Error in Javascript programming | tracking progress bar

After stumbling upon this code snippet at this link, I was eager to delve deeper into the world of JavaScript and jQuery. However, upon implementing these codes, I encountered a perplexing issue. The progress bar and continue buttons seem to be non-funct ...

Error code TS7053 occurs when an element implicitly has an 'any' type because a string expression cannot be used to index an empty object

I have implemented a code snippet that sorts items into groups based on their first character. For example, if the array of item looks like this: {name: 'Foo'} {name: 'Bar'} {name: 'Baz'} The expected result should be: B: ...

When using Javascript in a JSP page, it may not always read every element within an array

A project I'm currently working on involves developing a web application that prompts users to input estimated costs for various items. To accomplish this task, I am utilizing a JavaScript function to generate the necessary fields dynamically. var fi ...

Issue with peculiar circumstances regarding the JSON object and generating a chart, can you pinpoint what's amiss?

When sending data (values and dates) from a hard-coded function, everything works fine - the JSON file is populated and the chart is displayed. However, when I send data from the database, the JSON file is populated but the chart does not appear. Here is ...

What is the best way to retrieve information from a different table in order to establish a condition and form a relationship in Laravel and Vue?

Seeking assistance with website development. How can I retrieve data from the cycles table to establish a conditional relationship with the mortalities table? The information in the cycles table includes: $table->increments('id'); $table ...