Encountering an error when using the Vue 3 TypeScript Composition API for style binding with an asynchronous

I utilized nexttick alongside an async method to update a DOM element.

However, I am encountering issues with returning the correct style type.

An error message pops up stating:

error TS2322: Type 'Promise<{ maxHeight: string; }>' is not assignable to type 'StyleValue | undefined'. Type 'Promise<{ maxHeight: string; }>' is missing the following properties from type 'StyleValue[]': length, pop, push, concat, and 28 more. 

<template>
  <div :style="getHeight(i)" class="demo" v-for="i in [1,2]">Hi</div>
</template>

<script lang="ts">
import {defineComponent, reactive, nextTick} from 'vue'

export default {
  setup() {
    const getHeight = async (i: number) => {
      await nextTick()
      return {maxHeight: '12px'}
    };
    return {getHeight}
  }
}

</script>

<style>
.demo {
  border: 1px solid red;
}
</style>

https://i.stack.imgur.com/prEQw.png

Answer №1

Unfortunately, achieving your desired outcome is not feasible - consider exploring the concept of Methods

It's important to note that methods invoked from a template should refrain from causing any side effects, such as altering data or initiating asynchronous tasks. If you are tempted to do so, it may be more appropriate to utilize a lifecycle hook instead.

Answer №2

Due to the nature of getHeight being an async function, it automatically outputs a Promise. The style binding specifically requires objects with CSS style properties, known as StyleValue, hence the error when using a Promise.

However, in this scenario, there is no necessity for async/await as demonstrated in the updated code snippet below that can be viewed here:

export default {
  setup() {
    //const getHeight = async (i: number) => {
    //  await nextTick()
    //  return {maxHeight: '12px'}
    //};

    const getHeight = (i: number) => {
      return {maxHeight: '12px'}
    };
    return {getHeight}
  }
}

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

Unexpected Issue: Angular 12 Encounters JIT Compiler Unavailability

Lately, I've been encountering a persistent issue with an error message: Uncaught Error: JIT compiler unavailable. Ever since I upgraded from Angular version 8 to 12, whenever I run the ng build --prod --output-path = dist command and build Angular, e ...

Styling your Vuetify V-data-table with CSS

Struggling to add extra spacing between table rows, despite inspecting the page and verifying that my styles are not being overridden. Have read other Vuetify posts on applying CSS but still no luck. Any suggestions for why I can't style my table as d ...

Custom type checker that validates whether all properties of a generic object are not null or undefined

In an attempt to create a user-defined type guard function for a specific use-case, I am faced with a challenge: There are over 100 TypeScript functions, each requiring an options object. These functions utilize only certain properties from the object wh ...

The specified argument, 'void', cannot be assigned to a parameter that expects 'SetStateAction | undefined'

Currently, I am engaged in a TypeScript project where I am fetching data from an endpoint. The issue arises when I attempt to assign the retrieved data to my state variable nft using the useState hook's setNft function. An error is being thrown specif ...

Tips for connecting a Vuetify v-menu to its parent element within a list that can be scrolled

Within the project I am working on, there exists a scrollable inventory of items. Each item possesses a menu that is triggered open when the respective activator button is hovered over. By default, v-menu components are connected to the v-app element, ser ...

ESLint's no-unused-vars rule is triggered when Typescript object destructuring is employed

I'm encountering an issue with my Typescript code where I am destructuring an object to extract a partial object, but it's failing the linter check. Here is the problematic code snippet: async someFunction(username: string): Promise<UserDTO> ...

Encountering an error of undefined when trying to access the index parameter while looping through objects in vue

Take a look at the code snippet below. Here I am using v-for to iterate over the object. I am attempting to access the index parameter but it is coming up blank. <a href="#" class="list-group-item" v-for="(event, key, index) in events"> The ind ...

Navigating collisions in the ECS architecture: Best practices

I'm currently developing a game using typescript and the ECS design pattern. One of the challenges I'm facing is handling collisions between different entities within the game world. I have an entity called Player which comprises several componen ...

Creating a dynamic data table in Vuetify using Vue.js by making an API call

Could anyone provide me with an example of how to create a dynamic data table using Vuetify in Vue.js? I have checked the official documentation but couldn't find any examples. ...

Encountering a Typescript issue with the updated Apollo server version within a NestJS application

After upgrading my nestJS application to use version 3.2 of apollo-server-plugin-base, I encountered two TypeScript errors related to a simple nestJS plugin: import { Plugin } from '@nestjs/graphql' import { ApolloServerPlugin, GraphQLRequest ...

What is the reason behind TypeScript's lack of reporting an incorrect function return type?

It's surprising to see that TypeScript 4.4.3 does not identify an invalid type for the callback function. It makes sense when the function returns a "non-promise" type, but when it returns a Promise, one would expect TypeScript to recognize that we ne ...

What is the process of deploying Angular Server Side Rendering (SSR) build files to Azure Web App service using FileZilla FTP?

I'm currently working on Angular SSR and utilizing the Angular official sample project for testing purposes. Steps for building the Angular SSR project: Execute npm run build:ssr This will automatically generate the dist folder, which contains both ...

Struggling to integrate authentication and authorization features into a ReactJS application with Microsoft Azure AD or Database login functionality

We have an application built on React v18 with a backend that includes a Web API and SQL Server database. Our requirement is to authenticate and authorize users using either MS Azure AD or the database. If a user attempts to log in with a username and pas ...

Troubleshooting Node.js TypeScript breakpoints in Visual Studio Code

I've attempted multiple solutions, but none seem to be working for me. Although the code is running, I'm having trouble setting breakpoints and debugging it. Can you offer any assistance? Below is the configuration script I've tried in VSCo ...

Issue with minifying AngularJS and TypeScript route configuration for safe minification

Currently, I have a package containing multiple js files that were created from typescript files. However, when I attempt to apply minification to the package, the webpage encounters errors. The error message displayed on the Chrome console is: Uncaug ...

Trouble loading CSS file in Vue library from npm package

When using vue-cli to build a library (npm package) that functions for both SSR and client-side, everything seems to be functioning correctly except for one issue; the CSS only loads if the component is present on the page being refreshed. However, when ac ...

Vue.js is displaying one less item

Recently I started working with Vuejs and encountered an unexpected issue in my application. The purpose of my app is to search for channels using the YouTube API and then display those channels in a list. However, when I try to render the list of subscri ...

Adding items to the array is only effective when done within the loop

My approach involves retrieving data from an API using axios, organizing it within a function named "RefractorData()," and then pushing it onto an existing array. However, I have encountered a problem where the array gets populated within a forEach loop, a ...

Retrieve all the characteristics accessible of a particular course

I am facing a situation where I have the following class structure: class A { id: number propertyA: string constructor(id: number) { this.id = id } } let a = new A(3) console.log(SomeFunction(a)) // expected output = ['id', ' ...

Encountered a TypeScript error: Attempted to access property 'REPOSITORY' of an undefined variable

As I delve into TypeScript, a realm unfamiliar yet not entirely foreign due to my background in OO Design, confusion descends upon me like a veil. Within the confines of file application.ts, a code structure unfolds: class APPLICATION { constructor( ...