What is the best way to declare an array for use within a computed property?

Looking for a method to create a ref that can hold an array in my Vue 3 app built using composition API and typescript.

The array will be utilized in a computed property where objects will be pushed. However, I encountered an issue when trying to push objects into the array within the computed property:

Error: Property 'push' does not exist on type 'Ref<[]>'

This is the current code snippet I am working with:

const myArray = ref<[]>([]);

const myComputed = computed(() => {
  if (propertyOne) {
    myArray.push({ id: 'autoId0', path: 'myPath' })
  }
  return myArray
})

I have also attempted using let myArray = [] inside the computed property but the array remains empty. Any advice or suggestions would be highly appreciated!

Answer â„–1

Let's start by correcting the mistake you made:

The error message "Property 'push' does not exist on type 'Ref<[]>'" indicates that...

Consider the following examples:

const stringValue: string = ''
const numberValue: number = 123

If you do not specify the type, TypeScript will infer it based on the initial value, for example:

const impliedStringType = ''
const impliedNumberType = 123

In the case of declaring a reference to an array:

const myArrayRef = ref([])

The implied type would be Ref<[]>, where Ref is an object containing an array.

To use the push method, you need to access the value property of the ref:

myArrayRef.value.push()

Now, let's discuss your usage of computed:

Computed properties should represent derived values that are free from mutations. If you need to modify an array based on certain criteria and return a new copy:

You can achieve this by creating a computed array while avoiding direct mutation of the original array:

const myArrayRef = ref([])

const myComputedArray = computed(() => {
    const computedArray = [...myArrayRef.value]

    if (criteria) {
        computedArray.push(123)
    }

    return computedArray
})

This approach prevents mutating the original array directly when the criteria change, maintaining data integrity.


For hands-on practice and further exploration, check out the Vue Playground demo links provided above!

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

Typescript and Apollo Client return types intertwined

My goal is to create a simple function within a class that generates an Apollo Client. Below is the code I have implemented: import appConfig from 'config/app-config'; import { ApolloClient, InMemoryCache, createHttpLink } from '@apollo/clie ...

"Using VueJS to allow for easy data editing directly from a table and redirect

I currently have 3 pages set up for my project: 1- The first page is a list displaying all the data in a table format. 2- The second page allows me to add new data (currently using dummy data in the code). 3- The third page is supposed to be an edit page, ...

Utilize vue.js input field to search for a specific username within a constantly updating list of users

I have created an input search functionality to filter a list of users using PHP. Now, I am attempting to implement the same filtering feature in Vue.js so that when a user searches for a name, the filtered user will be displayed in the list. Below is the ...

Encountering an issue with creating an App Runner on AWS CDK

Attempting to deploy my application using App Runner within AWS via CDK. Utilizing the reference from https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-apprunner.Service.html. Upon deployment, encountering the following error: create_failed: R ...

Challenges with Vue 2 Cli CSP Build - Overcoming the Eval and new Function Obstacle

Recently, I had to update a static Vue application to comply with CSP requirements within the Vue 2 CLI environment. Despite researching extensively online, it became clear that in order for Vue to be CSP compliant, render functions and a runtime version ...

RxJS pipe operation ignoring observable

Currently, I am in the process of transitioning an app from Promises to RxJS and I could use some guidance on whether I am heading in the right direction. Situation: I have a ModalComponent that appears when an HTTP request is sent and disappears once the ...

Can anyone provide guidance on setting up a TypeScript service worker in Vue 3 using the vite-plugin-pwa extension?

I am looking to develop a single-page application that can be accessed offline. To achieve this, I have decided to implement a PWA Service Worker in my Vue webapp using TypeScript and Workbox. I found useful examples and guidance on how to do this at . Ho ...

Why does the onBlur event function in Chrome but fails to work in Safari?

I've encountered a problem with the onBlur event in react-typescript. To replicate the issue, I clicked the upButton repeatedly to increase the number of nights to 9 or more, which is the maximum allowed. Upon further clicking the upButton, an error m ...

Issue: Encounter of an unexpected error: Unhandled Promise Rejection Error: It seems that there is a TypeError occurring where the property '0' of a null object cannot be read

Ever since I started learning angular2, I have been experiencing this issue with my news.service. @Injectable() export class NewsServices { private news: News[] = []; constructor(private _http: Http) {} getSingleNews(id: string): Obs ...

Is it possible to customize text or images using the window.location method?

Imagine I have a scenario with 3 unique servers as follows: https://server-1.com https://server-2.com https://server-3.com In my Vue application, I want to dynamically change an image based on the server being used. Can I achieve this by utilizing someth ...

Leverage the data from a local JSON file within a web application built with Vue CLI 4.2.3

I need to use a JSON file to store some data and utilize them in the components. [ { "heroTitle": [ "Banner image", "assets/images/banner/sunset.jpg", "sunset.jpg" ], } ] The above JSON is an example, and below is my compone ...

Creating a customized bar chart in Angular using d3 with specific string labels - a step-by-step guide

I am currently implementing a bar chart using d3 in Angular to represent feelings ranging from very bad (1) to very good (5), with the feelings as labels on the yAxis. However, I am encountering an error message: Argument of type '(d: any, i: any) =&g ...

Steps for passing a text parameter to a component

Struggling to develop a component for Input that requires an extra parameter in the function to receive text for the label (as shown below). Not entirely sure if this is the correct approach and unsure about how to implement it. Here's the Component ...

Access specific properties of an object in TypeScript using dot notation with the

Can we use dot notation to extract nested object elements in TypeScript? interface Test { customer: { email: string; name: { firstName: string; }; }; }; type PickedTest = ExtractNested<Test, "customer.name.firstName"> ...

Developing a universal SDK wrapper for Firebase services (Firestore, Cloud Storage, and additional functionalities)

Currently, I am on the quest to discover an abstraction that can facilitate the seamless operation of Firebase products (specifically Firestore, Storage, and Analytics) across any platform (be it React Native, React, or Node.js). While considering the REST ...

Tips for obtaining a subset of `keyof T` where the value, T[K], refers to callable functions in Typescript

Is there a way to filter keyof T based on the type of T[keyof T]? This is how it should function: type KeyOfType<T, U> = ... KeyOfType<{a: 1, b: '', c: 0, d: () => 1}, number> === 'a' | 'c' KeyOfType<{a: ...

Is it possible to remove generic T in typescript if the mysql result value is an array but generic T is not an array?

type User = { name: string email: string } This is the code snippet, import type { PoolConnection, RowDataPacket, OkPacket } from "mysql2/promise"; type dbDefaults = RowDataPacket[] | RowDataPacket[][] | OkPacket | OkPacket[]; type dbQuery& ...

Troubleshooting Vue Js Form submissions to the backend server

As I work on developing my website, I encountered an issue with sending SignUp form data to my server using the post method. I attempted to use axios for this purpose, but unfortunately, it did not yield the expected results. Below is a snapshot of what my ...

Creating a Versatile Data Retrieval Hook in TypeScript for APIs with Diverse Response Formats

Currently, I am undertaking a movie discovery project that involves fetching data from two APIs: Tmdb movie site. These APIs have different response structures—one for movies and one for genres. In order to streamline my code and avoid repeating the same ...

Changing the order of a list in TypeScript according to a property called 'rank'

I am currently working on a function to rearrange a list based on their rank property. Let's consider the following example: (my object also contains other properties) var array=[ {id:1,rank:2}, {id:18,rank:1}, {id:53,rank:3}, {id:3,rank:5}, {id:19,r ...