What is the reason behind watches not triggering when there are changes in history?

<script setup>
import InputChat from '../components/InputChat.vue'
import Chat from '../components/Chat.vue'
import Layout from "@/components/Layout.vue";
import Sidebar from "@/components/Sidebar.vue";
import ChatVue from '@/components/Chat.vue';
import { ChatManager } from '../../lib/ChatManager';
import { ref, watch } from 'vue';
const manager = new ChatManager()
const historys = ref(manager.historys)

watch( historys ,(newHistory)=>{
  console.log("Watch execute");
  console.log(newHistory)
  console.log(historys.value);
},{deep:true})
const handleSentMessage = (value)=>{
  console.log(value + "Parent receive yet");
  manager.sentChat(value)
}
</script>

<template>
  <Layout>
    <template #sidebar>
      <Sidebar />
    </template>
    <template #chat>
      <Chat :history="manager.history"/>
    </template>
    <template #input-chat>
      <InputChat @sent-message = "handleSentMessage"/>
    </template>
  </Layout>
</template>


export class ChatManager {
   

  constructor() {
    this.url = import.meta.env.VITE_API_URL || 'http://localhost:11434/api'
    this.historys = [];
    
  }
  async sentChat(message){
    const messageTemplate = {
      request:{
        role:"user",
        content: ''
      },
      response:{
        role:'assistant',
        content:''
      }
    }
    
    try {
      messageTemplate.request.content = message

      
      this.historys.push(messageTemplate)
      const response = await fetch(`${this.url}/chat`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          model: "llama2",
          messages: [
            {
              role: "user",
              content: message
            }
          ],
          stream: false
        })
      });

      const data = await response.json();
      console.log(data)
       this.historys[this.historys.length-1].response.content = data.message.content
       this.historys[this.historys.length-1].response.role = data.message.role
      return data;

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

}

It is puzzling why the watch function does not trigger when the history changes. I expect it to execute whenever a change occurs in the history. Can someone provide assistance please?

Answer №1

ChatManager references a non-reactive array called historys, which cannot be observed.

To resolve this issue, the class should either explicitly use the reactive function for its fields, or make them reactive upon instantiation:

const manager = reactive(new ChatManager())
const historys = toRef(manager, 'historys')

watch(historys, ...)

Reactive classes come with various challenges that need to be addressed in order to ensure compatibility with Vue reactivity. Fortunately, none of these challenges currently apply to the ChatManager class.

Answer №2

For detailed information and instructions on how to utilize the 'Deep Watcher' feature, consult the official vue3 documentation.

Opt for the 'reactive' method over using 'ref'

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

Struggling to make the grunt.js task for postcss with autoprefixer function properly

I am currently facing issues with using postcss in conjunction with autoprefixer-core. Even though the css is being generated correctly, autoprefixer doesn't seem to be applying any prefixes. I have already installed postcss and autoprefixer via NPM ...

Transferring properties from React Router to child components on the server side

For my Isomorphic app using React, react-router v3, and material-ui, it's crucial to pass the client's user agent to the theme for server-side rendering. This is necessary for MUI to properly prefix inline styles. Initially, the root component o ...

Using inline SVG within a Vue.js component

Recently, I embarked on a Vuejs project using @vue/cli version 3.0.0-beta.16. In my Home.vue single file component, I encountered an issue while trying to import and add inline SVG to the template. The crux of the problem lies in the fact that vue cli alr ...

Transform a global JavaScript function into a global Vue.js function, compatible with the Vue Laravel framework

My JavaScript function displays a color border when required and changes the color if anything is inputted. It works fine in plain JavaScript but not in Vue. I need to use this function in Vue, on any place or component. app.js $('.req' ).on(&a ...

Utilizing React and Material-UI to Enhance Badge Functionality

I am exploring ways to display a badge icon when a component has attached notes. I have experimented with three different methods and interestingly, the results are consistent across all of them. Which approach do you think is the most efficient for achiev ...

Cypress OPENSSL_internal:NO_START_LINE error detected

Has anyone encountered this error before? I've already tried clearing the cypress cache and reinstalling it, but the error persists. I couldn't find a solution to resolve this issue. The version I am using is 6.5.0. Error: error:0900006e:PEM rou ...

Developing a Form Submission Feature Using JQuery Mobile

I'm having trouble submitting a form using JQuery Mobile. Currently, my code looks like this: <form action="#pagetwo" method="post" name="myform"> <input type="text" name="myname"> <input type="submit" value="submit" /> ... and th ...

Deactivating Bootstrap Modal in Angular

Looking for advice on managing a Bootstrap Modal in Angular 7 I have a Form inside a Bootstrap Modal that I need to reset when the modal is closed (by clicking outside of it). Despite searching on Google, I haven't been able to find a solution. Any ...

What is the method for eliminating quotes from a URL?

Changing the URL: history.replaceState('data to be passed', 'Title of the page', '<?php echo getAddress(); ?>/?usp-custom-14="'+urldates+'"&usp-custom-8="'+title+'"'); After making changes, it s ...

Efficiently sending data to Service Bus from an HTTP-triggered function

How can I link the output to service bus? I've configured an out binding in my Azure function: { "queueName": "testqueue", "connection": "MyServiceBusConnection", "name": "myQueueItem", "type": "serviceBus", "direction": "out" } I started ...

Automatically update the table in Python Flask every minute

I need help with my Flask code below. I want to automatically refresh the table data every 60 seconds. I have included the Setinterval function in HTML, but for some reason, it's not refreshing as expected. I'm struggling to pinpoint the exact is ...

Is it possible to rearrange the positions of 2 divs using solely CSS?

I have created a unique design. On iPad, I am assigning the class 'handHeld' to the <body>, which will trigger positional changes between optionsWrapper and #container using CSS classes I've defined below on jsfiddle.net. .handHeld d ...

What is the best way to compare two arrays that have elements of different data types?

Can someone help me compare two arrays in TypeScript to see if they are identical? I'm having trouble with the current code. Here's what I have: let props:(string|boolean)[]=['abc','def',true,false,'xyz'] let propsCo ...

The light slider feature is experiencing technical difficulties within the Bootstrap model

I am experiencing an issue with the Light Slider in a Bootstrap modal. Strangely, when I press F12 for inspect element, the Light Slider starts working. For more details and to see the link provided in the comment below, can anyone offer assistance, plea ...

OpenLayers had trouble handling the mouse event in Ionic

I am attempting to handle a double mouse click event on OpenStreetMaps by utilizing the code below: const map = new OpenLayers.Map("basicMap"); const mapnik = new OpenLayers.Layer.OSM(); const fromProjection = new OpenLayers.Projection("EPSG:4326"); // ...

The signature provided by the pusher is invalid: The expected HMAC SHA256 in hexadecimal digest is

The HTML file contains JavaScript code that calls the server for authentication. The code snippet from the HTML file is as follows: <html> <script> <head> var options = { authEndpoint: "api/pusher.json?socket_id=9900&channel_name ...

Using the v-html directive in a dynamic component with Vue.js

Is there a way to utilize the v-html directive with a dynamic component in Vuejs (3)? I'm encountering an issue where the content from v-html is not displaying. <component :is="Whatever" v-html="HTMLString"></component&g ...

What is the best way to read a file or Stream synchronously in node.js?

Kindly refrain from lecturing me on asynchronous methods. Sometimes, I prefer to do things the straightforward way so I can swiftly move on to other tasks. Unfortunately, the code below is not functioning as expected. It closely resembles code that was po ...

Having some trouble with node.js and the fs module when checking if a file exists. Let

I'm a bit confused about the various methods in Node.js to check if a file exists using fs(). One option is to use fs.readFile(): fs.readFile('somefile.html', function (err, data) { if (err) { /* file doesn't exist */ } else { /* ...

Tips for adding a background image using React refs?

Seeking assistance with setting a background for a specific div using react ref, this is my attempted code snippet: The component class structure as follows: import React from 'react'; import PropTypes from 'prop-types'; import class ...