Trouble with Vue3 Ref and Reactivity not displaying changes or updating

I'm seeking to grasp the concept of ref/reactivity in Vue3. Unfortunately, due to work constraints, we are unable to utilize any state management libraries.

The objective is to manipulate the number of objects in an array and have the ability to edit the contents of the array. However, I am facing an issue where the view does not update when using reactive. It does display properly with ref([]) but fails to update the row count.

Any insights or feedback would be greatly appreciated. Thank you.

List Component:

<template>
  <div>
    <p>Where's My Items</p>
    
    <q-virtual-scroll
    id="parent-scroll"
    class="scroll"
    style="height: calc(100vh - 285px);"
    :items-size="items.length"
    :items-fn="getSnippets"
    :virtual-scroll-slice-size="5"
    scroll-target="#parent-scroll"
    ref="items"
    v-slot="{ item, index }">
    <q-item :key="item.id" dense class="q-pa-none">
      {{ item.id }} - {{ item.d }}-{{index}}
      <ParentItem :parentItem='item'></ParentItem>
    </q-item>

  </q-virtual-scroll>

    <p>Count: {{ items.length }} </p>
  </div>
</template>
<script lang='ts'>
import { defineComponent, onMounted, watch, reactive } from 'vue';

// import {store} from 'src/controls/store';
// import {controller} from '../controls/control';
import {plane}  from '../controls/control';
// import controller from '../controls/store';
import { parentStruct, testStruct } from '../controls/types';
import ParentItem from './parentItem.vue'


export default defineComponent({
  name: 'CompositionComponent',
  components:{
    ParentItem,
},
  props: {
    aid:{
      type: Number,
      required:true
    }
  },
  setup(props) {
    let items =reactive(Array<parentStruct>());
    const {load,controller}=plane()
    const {getList}=controller()

    const getSnippets = (from: number, size: number) => {
      if (items.length === 0) {
        console.log('There is literally nothieng to load')
        return
      } else {
        console.log(`getsnippets ${from}  ${size}`)
      }

      return items.slice(from, from+size)
    }

    onMounted(()=>{
      console.log("parent list on mounted")
      load()
      items = getList(props.aid)??[]
      console.log(items)
    })

    watch(items,()=>{
      console.log('items change in watch')
    },{ deep : true})
        
    return { items,getSnippets};

  },
});
</script>

Child Component:

<template>
  <div>
    <TxtBoxComponent
      :txt="parentItem"
      @updateTxt="
        (text) => {
          modRepl(parentItem, text);
        }
      "
...

Controls:

import { reactive } from 'vue';
import { store } from './store';
import { parentStruct, testStruct } from './types';

const controller = () => {
  // const {store}=storage()
  const add = (parent: parentStruct) => {
    console.log('control add function');
    const items = store.get(parent.aid.toString());
    
    if (items) {
        items.splice(items.length,0,parent)
      store.set(parent.aid.toString(), items);

      console.log(`controller item length = ${items?.length}`);
    }
  };
  const del = (aid: number, id: number) => {
    const items = store.get(`${aid}`);
    if (items) {
      const idx = items.findIndex((item) => {
        return item.id == id;
      });
      items.splice(idx, 1);
    }
  };
...
import { reactive } from 'vue';

import { parentStruct } from './types'

export const store = reactive(new Map<string,parentStruct[]>())

Answer №1

After some testing, I made adjustments to the list component script as follows:

    setup(props) {
    const { load, controller } = plane();
    const { getList } = controller();

    let items = ref(Array<parentStruct>());
    const getSnippets = (from: number, size: number) => {
      if (items.value.length === 0) {
        console.log('No data available to load');
        return;
      } else {
        console.log(`getsnippets ${from}  ${size}`);
      }

      return items.value.slice(from, from + size);
    };

    onMounted(() => {
      console.log('List mounted successfully');
      console.log(items);
    });

    watch(
      items,
      () => {
        console.log('Items updated in watch');
      },
      { deep: true }
    );
    const stop = watchEffect(()=>{
      items.value = getList(props.aid)??[]
    })
    return { getSnippets, items  };
  },
});

I'm open to suggestions for improving this approach. Feel free to share your thoughts. 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

Is it necessary to ensure the complete loading of the API is complete before proceeding to the next function when using async/await?

I have some experience with Javascript and a little bit of VueJs knowledge. Currently, I am working with an array named tickets and receiving data from an API which returns two different data sets - tickets and user profiles. The ticket objects contain us ...

Jest Test - Uncaught TypeError: Unable to create range using document.createRange

my unique test import VueI18n from 'vue-i18n' import Vuex from "vuex" import iView from 'view-design' import {mount,createLocalVue} from '@vue/test-utils' // @ts-ignore import FormAccountName from '@/views/forms/FormAcco ...

Exploring Next.js 13: Enhancing Security with HTTP Cookie Authentication

I'm currently working on a web app using Next.js version 13.4.7. I am setting up authentication with JWT tokens from the backend (Laravel) and attempting to store them in http-only cookies. Within a file named cookie.ts, which contains helper functio ...

Accessing the parent element from a clicked child element within a nested v-for loop

Is there a way to access the parent element of a clicked child element using the @click method? For example: <div v-for="(item, index) in bubles"> {{item.name}} <div v-for="subItem in item.bubles"> <a @click="openModal(subItem)"&g ...

Searching for nicknames in a worldwide Jest arrangement?

Before running all test cases, I need to execute certain tasks only once. To achieve this, I have created a global function and specified the globalSetup field in my Jest configuration: globalSetup: path.resolve(srcPath, 'TestUtils', 'global ...

<T extends object>(value: T): T, but with the type changing from null to string

I discovered a tool called pathmirror that transforms objects like: {a: {b: null} } to {a: {b: 'a.b'} This is particularly useful for naming Redux actions. I'm wondering how I can create a type definition for this? Currently, my declarat ...

Angular Component - Array missing initial value in @Input property

Having trouble transferring values between components? I'm currently dealing with a situation involving two components: report-form and comment-form. The report form contains an array of comments, displaying a list of comments and a button for each on ...

"Exploring the world of Vue3 and Pinia: A guide to showcasing

I have a store called pinia with the following actions: actions: { async addCompany ( company ) { await axios.post('/api/companies.json', company) .then( (response) => { this.companies.pu ...

"Revamping Your Design: The Power of Angular 4

I am working with two different layouts in my project: <div *ngIf="!loginPanel" class="login1"> <a (click)="showLoginPanel()">Login</a> </div> <div *ngIf="loginPanel" class="login2"> <input type="text" placeholder="user ...

Unable to retrieve the Vuex-stored state in the ~/plugins/axios.js file

Having trouble retrieving the token stored by Vuex in ~/plugins/axios.js. Would greatly appreciate it if you guys could give it a look for me. This is my Vuex configuration: ~/store/index.js export const state = () => ({ authUser: null, token: nul ...

Could you provide insight into the reason behind debounce being used for this specific binding?

function debounce(fn, delay) { var timer return function () { var context = this var args = arguments clearTimeout(timer) timer = setTimeout(function () { fn.apply(context, args) }, delay) ...

Transfer content within <pre> tags to the clipboard using a Vue.js application

I am currently developing a Chrome extension using Vue.js where I aim to copy the content within a pre tag section to the clipboard with the click of a button. By assigning an element ID to the pre tag, I can retrieve the content using a copyToClipboard() ...

Is it possible to choose the inverse of a user-defined type in Angular?

Is it possible to retrieve the opposite of a specified custom type within a variable using Typescript? For example, if I define a type like this: type Result = 'table' | 'grid'; Then any variable with the type Result can only be assign ...

Loop through a collection of map instances in TypeScript

In my TypeScript code, I am making a call to an API method in a Java class that returns a list of maps. The TypeScript file includes the code snippet below. When attempting to retrieve data from dataBody, it displays as [Object Object]. I need assistance ...

Guide on creating several TypeScript interfaces that share identical type structures

export interface UserFailureResponse { statusCode: number statusMessage: string } export interface UserCreateResponse { statusCode: number statusMessage: string } export interface AuthCheckResponse { statusCode: number statusMessa ...

Eliminating the use of am/pm and implementing a 24-hour format on the x-axis of a time series

Currently, I am attempting to create a time series plot with second precision in the format of HH:mm:ss (24 hours per day), as indicated in the documentation provided by moment js. However, I have encountered an issue where the format I specify is not bei ...

Discovering the JavaScript source file for a package using WebStorm and TypeScript

In my TypeScript project, there is a usage of Express with the following method: response.send('Hello'); I am interested in exploring the implementation of the send() method. However, when I try to navigate to the source code by ctrl+clicking o ...

Distribute a TypeScript Project on NPM without exposing the source code

Issue: My library consists of numerous .ts files organized in structured folders. As I prepare to publish this library, I wish to withhold the source (typescript) files. Process: Executing the tsc command results in the creation of a corresponding .js fil ...

Having trouble establishing a connection with SignalR on my backend, it just doesn't seem to work properly

I am currently working on a project where I am using Vue with TypeScript and @microsoft/signalr. My goal is to create a chat feature using SignalR, and on the backend, I am utilizing C# with ASP.NET Core and docker. Here is the code snippet I have impleme ...

What is the best way to create a straightforward interface using TypeScript?

Although I'm sure this question has been asked before, I couldn't find the answer on Google or SO. So here it goes: I am looking to create an interface with a key named id of type number. Additionally, there may be other keys with unknown names ...