Vue does not display changes in the DOM when it is being mutated

I am currently working on incorporating a chat feature into my application, utilizing Typescript, Firebase, and Pinia. Users are able to create and join chat rooms where they can exchange messages. However, I am facing an issue where the DOM does not update automatically after sending a message; instead, I have to manually reload the page each time. I attempted to use a ref in the store within the currentChatRoom and implemented a watcher, but unfortunately, it did not resolve the problem.

This is an overview of the chatStore:

import { defineStore } from 'pinia'
import axios from 'axios'
import type { ITask, INewtask } from "../types/Task"
// Remaining code omitted for brevity

Below is an excerpt showcasing the component responsible for displaying the messages:

<template>
    <div class="chat-container">
        <div> Chat </div>
        <div> {{ chatStore.chatRoom.createChatName }}</div>
        <div> {{ chatStore.joinChatName }}</div>
        <h4>Messages:</h4>
        <div
            v-for="(message, index) in messagesArr"
            :key="index"
        >{{ message.messages }}</div>
    </div>
    <form class="chat-input">
        <input
            type="text"
            v-model="chatStore.messageInput"
            name="messages"
            placeholder="write something..."
        >
        <button @click.prevent="chatStore.SendMessage()">Send</button>
    </form>
</template>

<script setup lang="ts">
import useChatStore from '@/stores/chat'
// Remaining script content omitted for brevity
</script>

<style>
.chat-input input {
    width: 100%;
}

.chat-container {
    display: flex;
    height: 100%;
    flex-direction: column;
    align-items: center;
}
</style>

Answer №1

Consider utilizing computed to enhance your message handling

const messagesArray = computed(()=>chatStore.currentChatRoom.messages)

If you need to update the messages, try this approach

const messagesArray = computed({
   get: () => chatStore.currentChatRoom.messages,
   set: (newValue) => (chatStore.currentChatRoom.messages = newValue)
})

Answer №2

I encountered the issue and identified the root cause. I mistakenly assigned an already reactive value to a variable, specifically chatStore.currentChatRoom.messages, causing it to lose its reactivity. To resolve this, I needed to directly iterate through the variable like so:

  <h4>Messages:</h4>
        <div
            v-for="(message, index) in chatStore.currentChatRoom?.messages"
            :key="index"
        >{{ message.messages }}</div>
    </div>
    <form class="chat-input">
        <input
            type="text"
            v-model="chatStore.messageInput"
            name="messages"
            placeholder="write something..."
        >
        <button @click.prevent="chatStore.SendMessage()">Send</button>

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

Test the HTML element using ngIf async call in Angular 2 with Jasmine unit testing

As I work on writing unit tests for an HTML div with a condition using *ngIf, I come across a specific scenario. <div *ngIf="clientSearchResults$ | async as searchResults" class = 'fgf' #datalist id="mydata" > <app-client-list id=" ...

Develop a specialized data structure for rows in ag grid that can adapt to changes

I have been working on creating an independent component using ag-grid. The column definitions are passed to this component from my application as input properties, defined like this: interface ColumnDef { field: string; headerName: string; } @Input() ...

Using ngFor to display images with src attribute, merging information from two different properties within the loop

One issue I am facing involves an array with properties: export interface IGameTag{ name: string; relativePath: string; filename: string; } I understand that it is possible to include the filename in the relativePath like this: <div *ngFor=" ...

Having difficulty accessing a private channel with Laravel and Vue.js due to pusher integration

I've successfully set up a notification system and everything is working fine when I send notifications to Pusher. However, I encounter an error when trying to listen on a private channel. Below is the code from my bootstrap.js file in Laravel-Echo: ...

Transforming data objects into simplified interfaces using Typescript

Issue Explanation Current data: { "field1": "value", "field2": 3, "field3": true, "extraField": "toRemove" } An interface is defined as follows: export interface MyInterface { field1: string; field2: number; field3: boolean; } Objective ...

Executing vitest on compiled javascript files

Currently facing issues running vitest on compiled JavaScript. Numerous errors are appearing, such as: TypeError: Cannot read properties of undefined (reading 'spyOn') TypeError: Cannot read properties of undefined (reading 'mock') and ...

Tips for properly importing types from external dependencies in TypeScript

I am facing an issue with handling types in my project. The structure is such that I have packageA -> packageB-v1 -> packageC-v1, and I need to utilize a type declared in packageC-v1 within packageA. All the packages are custom-made TypeScript packa ...

The compiler does not recognize the TSConfig option 'lib' - please review and correct

I have inherited an angular 1 project written in typescript version 1.8.10. However, I am encountering compilation issues with the following error message: Unknown compiler option 'lib' If I remove the "lib" line, a cascade of other errors suc ...

Can files be uploaded to the public folder in Vue.js?

Is there a method for uploading a file to the Vue.js public folder and then saving the filename in the database using an API? For example, saving an image in the Vue.js public folder and then storing the image name in the database. I would greatly apprec ...

Stop MatDialog instance from destroying

In my application, I have a button that triggers the opening of a component in MatDialog. This component makes API calls and is destroyed when the MatDialog is closed. However, each time I open the MatDialog for the second time by clicking the button agai ...

Analytics dashboard does not display Firebase ITEM_NAME

I'm currently analyzing the usage of different parts of my app, and to do this I've implemented a logEvent as shown below: Bundle bundle= new Bundle(); bundle.putString(FirebaseAnalytics.Param.ITEM_CATEGORY, "action"); bundle.putString(FirebaseA ...

fill the designated column in accordance with the specific criteria

Is there a method to automatically fill in a specific column based on certain conditions? I am looking to populate the column labeled [Last] when the column index is 1 and the corresponding name is [First]. import {Component, OnInit} from '@angular ...

I want to create a feature where a video will automatically play when a user clicks on a specific item in a list using Angular

Currently, I'm working on a project that involves displaying a list of videos and allowing users to play them in their browser upon clicking. The technology stack being used is Angular 2. Below is the HTML code snippet for achieving this functionalit ...

What is the best way to set a prop as the value of an input using Vue.js 2?

Here is my Vue component: <template> <div class="modal" tabindex="-1" role="dialog"> <form method="post" :action="baseUrl+'/product/edit'"> ... <input type="hidden" name="product_id" :val ...

What allows us to use the array access operator ([]) on objects without causing an error?

During my code refactoring process, I encountered an unusual behavior from the TypeScript compiler that has left me puzzled. interface IPoint { x: number; y: number; } let a: IPoint = { x: 5, y: 10 }; let b = a[0]; console.log(b); Upon compiling ...

Tips for sending code confirmation in Amazon Cognito identity using nest.js

Having some issues with implementing AWS Cognito login in Nest.js? Check out this helpful guide on token validation: https://medium.com/weekly-webtips/token-validation-with-aws-cognito-and-nestjs-6f9e4088393c. I need to add a feature where users receive ...

Mastering the process of importing AngularJS submodules in TypeScript

Currently, I am in the process of structuring an AngularJS (Angular 1) project using TypeScript. To compile TypeScript & ES6 to JavaScript, I have set up webpack. In my webpack configuration, I only compile the "app.ts" file and any other files it imports ...

Using Promise.all for multiple function calls

I have several functions set up like this: private async p1(): Promise<Result> { let p1; // Do some operations. return p1; } private async p5(): Promise<void> { // Make a call to an external API. } Some of these functions c ...

Retrieve identical values from an array and display them using Vue.js

I am working with a product array that includes id, name, and category data for 5 products. For example, let's say there are 3 products assigned to the mobile category and 2 products assigned to the computer category. What is the best approach to rend ...

billboard.js: The 'axis.x.type' property is conflicting with different data types in this context

axis: { x: { type: "category" } }, An issue has arisen: The different types of 'axis.x.type' are not compatible with each other. The value of 'string' cannot be assigned to '"category" | &qu ...