Is it necessary in Vue 3 to include the entire object structure when setting up a reactive value?

If I need to establish an empty value in my Pinia store to store the current subscription model the user is viewing, it should be null if the user is not on a subscription detail page.

Process: When the user clicks on a link to view subscription details for ID 1, I will trigger an action in the store to fetch the details for subscription ID 1 and assign the object returned by the endpoint to the reactive variable.

export const useSubscriptionStore = defineStore("subscriptions", () => {
  let currentSubscription: Ref<SubscriptionModel> = reactive(null); // Need to handle both cases!

  async function loadSubscription(subscriptionId) {
    const { $api } = useNuxtApp();

    const { data } = await useAsyncData(() =>
      $api.subscriptions.getSubscription(subscriptionId),
    );
    currentSubscription.value = data.value;
  }

  return {
    loadSubscription,
  };
});

Should I set the reactive variable declared in line 2 to match the object structure expected from the backend? Is it possible to have a reactive variable that can hold either null or an object?

In Vue 2, we could utilize Vue.set()

Answer №1

The accurate format is SubscriptionModel | null, and it ought to be ref instead of reactive, especially considering the type is already Ref. API functions are typically generics in TypeScript, enabling inference of the type. Opting for const over let helps prevent inadvertent reassignment, which frequently leads to a loss of reactivity.

The revised version should be:

const currentSubscription = ref<SubscriptionModel | null>(null); 

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

How to set the default option in a select dropdown using Angular and Types

It's been a while since I last worked with Angular and now I'm tasked with working on an existing system. I introduced an NgModal dialog to send text messages, designed as shown here: https://i.sstatic.net/67U1M.png Below is the code snippet I ...

Utilizing the power of generics alongside index type manipulation

After successfully running this code: const f = <T extends string>(x: T) => x; f(""); interface Dictionary<T> { [key: string]: T; } const dict: Dictionary<number> = { a: 1 }; I anticipated the following code to work as well: interf ...

Error: zsh is unable to locate the command, even after defining it in package.json bin and installing it globally

I attempted to create a command-line application using TypeScript. Below is the code I have written: //package.json { "name": "jihea-cli", "version": "1.0.0", "description": "", "main": "index.ts", "bin": { "cli": "./bin/index.ts" }, // ...

Retrieve the individuals within the delimiter

Looking for a solution to modify the characters within square brackets in a given string. For instance, I have a string that looks like "[A] [B] this is my [C] string". How can I update these bracketed characters by adding or removing brackets? ...

Unable to access specific data from the JSON string retrieved from the backend, as it is returning a value of undefined

After receiving a JSON string from the backend, my frontend is encountering issues when trying to index it post using JSON.parse(). The indexed value keeps returning as undefined, even though it's a JSON object literal and not within an array. For th ...

Combining webpack encore and Symfony, we can easily integrate VueJS single file components (SFC) into our project's style

Working on a Symfony5 project, I am incorporating the VueJS framework using Single File Components (SFC). Within my VueJS component styles, I need to utilize the "url" css rule to define file paths. Specifically for designing a div with background-image ...

What event is triggered in VueJS when a new click or reset changes the component state?

I am currently working with 2 components on the same page: 1. Item List 2. Lightbox, a classic HTML lightbox without any added Vue.js components I am passing my item ID through a prop to the lightbox, and it is functioning correctly. When I click on an it ...

Ditching the subscribe(...) method in Angular by opting to return a string value instead of an

I have been tasked with exploring how to make a service call and return the final result instead of an observable. Within the service, there is a method structured like this: getToken(name: string, pass: string): string { const url = "https://localhost: ...

Switching between play and pause for the video element using a component for the child

Trying to toggle the play/pause of a child video by clicking on a parent div can be challenging, especially when dealing with multiple instances of the same div and video. A normal function may only work for one specific video, as mentioned by @ken. I hav ...

Is it possible for TypeScript to automatically detect when an argument has been validated?

Currently, I am still in the process of learning Typescript and Javascript so please bear with me if I overlook something. The issue at hand is as follows: When calling this.defined(email), VSCode does not recognize that an error may occur if 'email ...

Creating Instances of Parameterized Types

Consider the following scenario: class Datum {} An error message (error TS2304: Cannot find name 'T') is encountered when attempting the following: class Data<T extends Datum> { datum: T constructor() { this.datum = new ...

Angular HttpClient mapping causes the removal of getters from the target object

Utilizing the HttpClient to fetch Json data from an API, I am utilizing the autoMapping feature of the HttpClient to map the json response to a specified object in this manner: this.httpClient.post<Person>(url, body, { headers: headers, params: http ...

React is not displaying the most recent value

During the initial rendering, I start with an empty array for the object date. After trying to retrieve data from an influxDB, React does not re-render to reflect the obtained results. The get function is being called within the useEffect hook (as shown in ...

Showcasing an image stored in an HTML file on a Vue.js webpage

I'm currently facing an issue with displaying a local image saved in an HTML file on my Vue.js page. I attempted to store the content of the HTML file into a variable using the code below: computed: { compiledHtml: function() { return this.a ...

Unidentified properties in mongoose query

Currently, I am utilizing MongoDB and Mongoose along with TypeScript. I have encountered an issue with the following scenario: Here is the model definition I have created: export default conn.model<AdminInterface & Document>('Admin', a ...

Dynamic HTML binding with v-model in Vue JS allows for seamless two-way

I recently incorporated Vue Js into my main MVC application. I want to be able to bind a Vue Js v-model to dynamically loaded HTML from a partial view. For example, in my partial view, I have the following: <input type="text" id="firstNam ...

Struggle with Loading Custom Templates in Text Editor (TinyMCE) using Angular Resolver

My goal is to incorporate dynamic templates into my tinyMCE setup before it loads, allowing users to save and use their own templates within the editor. I have attempted to achieve this by using a resolver, but encountered issues with the editor not loadin ...

Enhancing TypeScript type definitions for the Response.render() method in Express

Struggling with enhancing the type safety of my Express project by extending the Response.render function. import { Response } from "express"; import { Product } from "../models/Product.interface"; export interface ProductListResponse ...

Combining multiple arrays of numbers in Typescript into one aggregate

I am looking to combine multiple number values from different arrays in Typescript. My data model looks like this: export class DataModel { date : string; number : any; } The main class contains an array of DataModels: export class CountryData ...

Modifying Record values based on a specific property's conditions

I am looking to create a filtering system with various filters, each consisting of a label, value, and sometimes the options variable. The inclusion of the type property is intended for differentiation. However, I have encountered an issue with the follow ...