Utilizing the composition API to dynamically update the state of an array in Vue

I am working on implementing a state using the composition API in Vue 3 with the code in the file below:

// useNotifications.ts
const state = reactive<Array<Notification>>([]);

export function useNotifications() {
  return {
    state,
    add: (notification: Notification) => {
      state.push(notification);
    },
  };
}

The notifications from this state are displayed in the HTML as shown below:

// TheNotifications.vue
setup() {
    const notifications = useNotifications();

    let first = notifications.state[0];

    return {
      first,
    };
  },

New notifications are added when a form is submitted like this:

// SomeForm.vue
notifications.add({ type: "success", text: "Food added" });

However, the TheNotifications component does not reflect the changes when new notifications are added. I have attempted using different methods, such as toRef, but have not been successful. As someone new to the composition API, I am wondering what I may be missing.

Answer №1

reactive has some limitations when working with Arrays within the composition api. For more information on this topic, you can check out a similar discussion here.

To overcome this limitation, it is recommended to use ref instead of reactive. I have personally tested this method in a few applications and can confirm that it works effectively. For example, you can write:

const state = ref<Array<Notification>>([]);
, and it should work seamlessly. Generally speaking, use ref for anything other than objects, and reserve reactive for handling objects. While the topic is more complex than this, following this guideline will ensure smooth functionality.

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

Transferring information using TypeScript

My issue arises when transferring data from HTML in the following format Karbohidrat :{{karbohidrat}} <button ion-button (click)="cekHalamanMakanan('karbohidrat')">View carbohydrate foods</button> <br> Then, I retrieve the kar ...

What is causing the "excessive stack depth" error in this JSX code?

Exploring Next.js' TypeScript (4.2.3) functionality, I am utilizing it to compile the React component provided below. const Component = (): JSX.Element => { const categories = ['Fruit', 'Vegetables']; return ( <ul> ...

When TableRow's onSelectChange is activated, it correctly selects the entire Table Group instead of an

In my React TypeScript application, I am working with an Array of Objects to populate a table. Each table row is grouped by category, and within each row, there is a select box that triggers an event to select all items with the same category: https://i.s ...

Required attributes not found for data type in TypeScript

When the following code snippet is executed: @Mutation remove_bought_products(productsToBeRemoved: Array<I.Product>) { const tmpProductsInVendingMachine: Array<I.Product> = Object.values(this.productsInVendingMachine); const reducedPro ...

Experiencing problems with images in vue-cli? Look no further, as we dive into troubleshooting with

During development, I encountered an issue with my code that uploads images to a server folder and stores references in a mysql database. When transitioning to production, the images became undefined, resulting in 404 errors. I came across the VUE Static ...

Ways to access the types of function parameters

Obtaining a method's parameter types using ReflectAPI is simple: Reflect.getMetadata('design:paramtypes', target, propertyKey); However, the challenge arises when trying to retrieve a function's parameter types as it constantly return ...

Encountering a white screen when attempting to pass props in history mode with Vue Router

During my Vue Router development process, I encountered a situation where one of my routes required a prop with an ID. To address this, I added the necessary configuration: const routes = [ { path: '/user/:id', name: 'user', ...

Incorporate an external JS file (File A) that is dependent on another JS file (File B) into a TypeScript file within the context of Angular 4

Working on an Angular 4 project, I recently installed two external JS libraries using npm. They are now in the node_modules folder and usable in another TS file within my project. The issue arises because import B requires import A, preventing me from effe ...

The 'split' property is not present on the 'string | number | {}' type

Just starting out with Typescript and I've encountered an error stating that the split method does not exist on type number. I've tried narrowing down the type by checking the value's type, but so far it hasn't been successful. Below is ...

How to configure mat-sort-header in Angular Material for mat-table

My current table is created using Angular Material: <mat-table *ngIf="!waiting" class="table-general table-summary" #table [dataSource]="dataSource" matSort> <mat-header-row class="header_row" *matHeaderRowDef="headerKeys"></mat-header ...

What steps should I take to enable the camera view in ngx-scanner?

I am currently working on an app that utilizes a QR code scanner. To implement this, I am using the ngx-scanner component, which is a modified version of Google's ZXing scanning library designed for Angular. However, I am encountering an issue where ...

Typescript fetch implementation

I've been researching how to create a TypeScript wrapper for type-safe fetch calls, and I came across a helpful forum thread from 2016. However, despite attempting the suggestions provided in that thread, I am still encountering issues with my code. ...

What is the best way to invoke a function only once in typescript?

Struggling to implement TypeScript in React Native for fetching an API on screen load? I've been facing a tough time with it, especially when trying to call the function only once without using timeouts. Here's my current approach, but it's ...

Troubleshooting a Missing Call Display Issue in Angular2 API

Greetings, I am a new web developer and I have been tasked with creating a prototype Inventory Page using Angular2. Please bear with me as my code may not be perfect. In the snippet below, you'll notice that we are calling our base back-end API (&apo ...

Exploring the capabilities of SWR for updating data in Next JS

I have been working on creating a component with an active property that can be toggled by the user as many times as they want. Since I am using Next.js, I decided to implement SWR for client-side rendering. However, despite my efforts over the past few da ...

One way to extract data from a Quasar table row using the @row-click event

Is it possible to retrieve the data associated with a row from a table using the @row-click event? How can I specifically access the id and name values of the row that was clicked in the example below? <q-table title="Treats" dense :dat ...

Accessing objects using string literals is restricted! I am encountering an issue while attempting to access the route parameter 'id' via a dynamic ID

Let's take a look at my custom [app-routing.modulse.ts] module: const appRoutes: Routes = [ { path: '', redirectTo: '/recipes', pathMatch: 'full' }, { path: 'recipes', component: RecipesComponent, child ...

Merging two arrays of objects from the same response in JavaScript

How can I efficiently merge two arrays of objects from the same response? let data = [{ "testLevel":"mid", "testId":"m-001", "majorCourse": [ { "courseName":"C++" ...

"Encountering a puzzling issue with Django Rest Framework where the path setup is functioning for one link but not for

I'm currently attempting to connect to my MySQL database using the Django REST backend. On my frontend, I'm using Vue with Axios. Specifically, I have a junction table called TeacherSubjectJunction, and I want to access it through the following p ...

An issue arises in vue.js where the v class binding takes precedence over other bindings and fails to properly remove

I have a game with a punching bag where I want to incorporate an animation class each time the bag is clicked. Once the health meter hits zero, I intend to replace the bag image with one depicting a burst bag. Things are running smoothly up until the poin ...