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

Error: The reference to 'ko' is not defined while loading with jQuery

After numerous attempts, I am still encountering the ReferenceError: ko is not defined issue while trying to load KnockoutJS using jQuery's getScript function. Below is the code snippet I have been testing to see if everything is functioning correctl ...

Can the function be executed without the need for ng-app?

After researching my AngularJS application, I discovered that having 2 ng-app tags in the html file means only the first one will be executed. In my code snippet below <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js"> ...

How to Invoke JavaScript Functions within jQuery Functions?

I'm working on a jQuery function that involves dynamically loading images and checking their width. I have two JavaScript functions, func1() and func2(), that I want to call from within the jQuery function in order to check the width of each image. T ...

Why am I encountering difficulties connecting to the Socket IO object in Node.js using Express?

Encountering a strange issue on the remote server side where everything works fine locally with a self-signed cert over https. However, when moving the code to the server, it works locally but not remotely. A node app is created and hosted on the server u ...

Discovering the smallest, largest, and average values across all properties in an array of objects

Given an array of objects with varying values, the task is to determine the minimum, maximum, and average of the properties in that array. For example, consider the following array: const array = [{ "a": "-0.06", "b": "0.25", "c": "-0.96", ...

Tips for retrieving page source with selenium Remote Control

Looking to Develop a Basic Java Web Crawler. WebDriver driver = new HtmlUnitDriver(); driver.get("https://examplewebsite.com"); String pageSource=driver.getPageSource(); System.out.println(pageSource); The result is as follows: <!DOCTYPE html PUBLIC ...

Tips for testing the onEnter and resolve functions of a ui-router state

I need help testing an Angular UI Bootstrap modal that is triggered from the onEnter function in the state below: .state("profile.index.edit.services", { url: "/edit/services/:serviceCode", parent:"profile.index", onEnter: ['$ ...

Vue.js parent component not receiving data emitted by child component

Below you will find the child and parent components. I am struggling to pass data from the child component to the parent component. Can you help me pinpoint where the issue may be? Child Component <template> <div> <v-btn class="r ...

Using the power of node.js to iterate through a loop of queries and execute

While I am running a for loop, within the loop itself I am executing a PostgreSQL query and storing the result in an array. However, I am unable to determine the order of execution. Here is my code: var array =[]; for(var i = 0 ; i< latitude.le ...

Redirecting to a hash in Vue-router with a specified timeout

My route configuration looks like this: { path: '/kontakt', redirect: '#contact', component: index }, as well as the scroll behavior: scrollBehavior(to, from, savedPosition) { if (savedPosition) { return saved ...

Converting text data into JSON format using JavaScript

When working with my application, I am loading text data from a text file: The contents of this txt file are as follows: console.log(myData): ### Comment 1 ## Comment two dataone=1 datatwo=2 ## Comment N dataThree=3 I am looking to convert this data to ...

Understanding the process of parsing JSON response using JavaScript

I am facing an issue with reading a JSON object in JavaScript. I have received this JSON object as a response and now I need to create a jstree based on it. Here is my JavaScript code: var repoId = $('#frmHdnV').val(); // variable to hold req ...

Using PHP to send asynchronous requests to the server can greatly enhance

I have almost completed my project, but I am facing an issue with reading the data sent to the server. function main() { jQ(document).on("keyup", "form input", function () { var data = new FormData(); var value = jQ(this).val(); da ...

Tips for maintaining previously accessed data when utilizing useQuery

I am currently working on incorporating a GET request using useQuery from the react-query library. Below is the relevant code snippet: import queryString from "query-string"; import { useRouter } from "next/router"; const { query } = ...

Using setTimeout with drag and drop functionality in HTML

I need a setTimeout function to be triggered only after dragging and dropping an image into a division, not before the drop occurs. ...

Problems with spacing in Slick slider and lazyYT integration

Utilizing lazyYT helps to enhance the loading speed of YouTube videos. Once loaded, these lazyYT videos are then placed within a slick slider. However, an issue arises where the videos stick together without any margin between them. To address this problem ...

The confirm() function shows up before the background on a blank layout

I'm facing an issue where whenever my confirm() function pops up, the alert box displays correctly but then the background turns blank. I've tried various solutions like moving the entire if statement to the bottom of the page or at the end of th ...

Retrieving information from an API and transferring it to the state in a React component

I am currently working on a random quote generator project, and I'm facing some difficulties in passing the API data to my state and also accessing it in the QuoteComponent through props. Despite following all the correct procedures, whenever I try to ...

Instead of using onload, activate function upon click instead

Upon page load, I have a function that executes: function loadData(page){ showLoading(); $.ajax({ type: "GET", url: "load_data.php", data: "page="+page, success: function(msg) { ...

Create an illustration of a canvas interacting with a database image source, but failing to display local images

When attempting to load an image onto a canvas, I encountered an issue. My code works without any errors when I use image.src="https://somelink", but throws a GET error when I try to import with image.src="../public/vercel.svg. Below is my c ...