Utilizing asynchronous operations dependent on the status of a separate entity

Dealing with asynchronous operations in Vue has been a challenge for me. Coming from a C# background, I find the async-await pattern more intuitive than in JavaScript or TypeScript, especially when working with Vue.

I have two components set up without using Vuex:

// App.vue
// ...
async beforeCreated() {
  console.log('connecting')
  await WebSocket.connect(...)
  console.log('connected')
}
// ChildComponent.vue
// ...
async mounted() {
  console.log('invoking')
  await WebSocket.Invoke(...)
  console.log('invoked')
}

The output I'm getting is as follows:

1. connecting
2. invoking
3. invoked
4. connected

This means that I am not properly connected and the Invoke operation fails. I've attempted using Vuex but without success. While connecting to the WebSocket is straightforward by using Actions and Mutations, the 'Invoking' part is where I struggle.

In an attempt to address this, I tried the following code snippet only to receive undefined:

// ChildComponent.vue
// ...
async mounted() {
  await this.$store.state.moduleA.webSocket.Invoke(...) // moduleA is defined but webSocket is not
}

Furthermore, utilizing Vuex's mutations and actions feels illogical since I'm simply calling a server-side procedure without changing the state of any object.

How should I properly implement this? I'm currently stuck on this issue and could use some guidance. It's worth noting that I am working with TypeScript.


HTML code for Vue components:

App.vue

<template>
      <child-component />
</template>

<script lang="ts">
import ChildComponent from './components/ChildComponent.vue';

export default Vue.extend({
  components: { ChildComponent },
  name: 'App',
  async beforeCreate()  {
    await this.$WebSocket.connect(...)
  }
});
</script>

ChildComponent.vue

<template>
  <div>something</div>
</template>

<script lang="ts">
import Vue from 'vue'
export default Vue.extend({
  name: 'ChildComponent',
  async mounted(): Promise<void> {
    await this.$WebSocket.Invoke(...)
  },
})
</script>

Answer №1

The main issue lies in a misunderstanding of async/await. It's essentially just a syntax sugar for Promises, so your code can be rewritten like this:

beforeCreated() {
  console.log('connecting')
  WebSocket.connect(...).then(() => {
    console.log('connected')
  });
}

Therefore, the beforeCreate hook exits at the await line and the Vue instance goes down on the next hooks. In this scenario, it is not advisable to rely on Vue hooks. Instead, utilize the Websocket event.

async beforeCreated() {
  Websocket.on('open', () => {
    this.websocketIsOpened = true; // ensure it is present in data()
  });
  await WebSocket.connect(...)
},
template: `
...
<ChildComponent v-if="websocketIsOpened" />
or 
<ChildComponent v-bind="websocketIsOpened" /> 

In the second approach, you may require an immediate watcher in the child component on this property to trigger the Invoke method.

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

Having trouble creating a scatter chart using vue-charts library

Whenever I try to render the chart, all I get is a blank page along with this error message: TypeError: Cannot read property 'getBasePixel' of undefined There seems to be an issue with my implementation in Vue.js even though I followed the ex ...

Best practices for managing CSV files in Next.js with TypeScript

Hello, I am currently working on a web application using nextjs and typescript. One of the features I want to implement is a chart displaying data from a csv file. However, I am not sure if using a csv file is the best choice in the long run. I may end up ...

Struggling to retrieve data with arrow function in Vue

I'm currently learning Vue and facing an issue with fetching data from an API to my component. I have a service class that successfully retrieves data from the API, as the API itself is working fine. Here's the code snippet: import IReview from & ...

Exploring Angular 2's EventEmitter for Event Handling and Debugging

My attempt at creating a basic event emitter doesn't seem to be functioning properly. Here's the code snippet: Main Component This is the main app component I have been working on: @Component({ selector:'my-app', templateUrl: ...

Using a variety of objects in TypeScript arrays

How to effectively implement a superior class in TypeScript for an array containing diverse objects that inherit from the same class, without triggering errors? This is my attempt: interface IVehicle{ modelName: string } interface ICar extends IVehi ...

Unit Testing in Vue.JS: The original function remains active even after using sinon.stub()

While unit testing my components (which are coded using TypeScript along with vue-class-component), I am utilizing Sinon to stub API calls. However, even after adding the stub to the test, the original method is still being invoked instead of returning the ...

Is it possible to integrate Swagger UI directly into a Vue component using Vue.js?

I recently encountered an issue while trying to render the contents of an uploaded API file in my Vue component. I came across a solution that involves using the Swagger client library, which you can find here: Swagger Client Library. If you're intere ...

Steps for transferring .pem files to Typescript outDir

I am currently working on a NodeJS project using Typescript, and I have encountered an issue with referencing .pem files to initiate an https server. The problem arises when my code is compiled, as the .pem files are not present in the output directory. ...

Navigating within Vue.js: Utilizing vue-router for seamlessly redirecting to targeted sections within a view identified by an ID

I am in the process of using a Home view and a Blog view. My goal is to utilize a <router-link> to transition from the Home view to a particular section within the Blog view. The specific section I am referencing appears as follows: <section id=&q ...

Issue with Jest mock function failing to trigger axios instance function causing it to return undefined

I initially found a solution on this StackOverflow thread However, I wanted to add my own helper function that generates a fresh Axios instance with the user's authentication token. Here is what I came up with: import axios from "axios"; c ...

When attempting to access http://localhost:3000/traceur in Angular 2 with the angular-in-memory-web-api, a 404 (Not Found) error

Hello, I'm encountering an issue with angular-in-memory-web-api. I have attempted to use angular2-in-memory-web-api in SystemJS and other solutions, but without success. I am currently using the official quickstart template. Thank you for any assistan ...

`In TypeScript Angular, encountering challenges with accessing object properties`

My TypeScript object looks like this const playlist: { tracks: Array<Track> } = { tracks: new Array<Track>() }; This is the Track interface I am working with interface Track { title?: string; album?: string; artists?: string; duration? ...

Utilizing Axios to make a GET request and showcasing the outcomes on HTML using Vue

Recently delving into Vue and Axios, I am in the process of fetching data from an API to display it within an HTML card. However, it appears that the data is being attempted to be displayed before being retrieved from the API, resulting in nothing renderin ...

The deletion of property '1' from the [object Array] is not possible

How to Retrieve a List in My Components Using Input : @Input() usersInput: Section[]; export interface Section { displayName: string; userId: number; title: number; } Here is the Value List : 0: displayName: "بدون نام" ...

The problem with Vue JS static links

I'm currently working with a Vue.js application (v2). I've noticed that if I skip visiting the root of the site, the sub-links do not work properly. For example: Visit: Then go to If I directly visit: I encounter the following error messag ...

Position components in Angular 2 based on an array's values

Hello all, I am a beginner in terms of Angular 2 and currently facing some obstacles. My goal is to create a board for a board game called Reversi, which has a similar layout to chess but with mono-color pieces. In order to store the necessary information, ...

Leveraging Next.js with TypeScript and babel-plugin-module-resolver for simplified import aliases

I am currently in the process of setting up a Next.js project with typescript. Despite following multiple guides, I have encountered an issue concerning import aliases. It's unclear whether this problem stems from my configuration or from Next.js its ...

Error message "Cannot find children property on type IntrinsicAttributes & RefAttributes<unknown>" occurring in a React component due to a Typescript issue

Issue: The specified type '{ children: string; severity: string; sx: { width: string; }; }' is not compatible with the type 'IntrinsicAttributes & RefAttributes'. The property 'children' is missing in the type 'Intri ...

Avoiding multiple HTTP requests on various subscribers in RXJS/Angular

I am currently utilizing the "mainData" service, which is composed of 3 key parts: currentPage is utilized by the paginator component for page navigation and can be updated dynamically. folders holds all folders within the current directory. This observa ...

Using Jest functions as object properties results in undefined behavior

I am faced with a challenge in my class where I need to mock an object along with its properties intercept(context: ExecutionContext) { const response = contect.switchToHttp().getResponse() // the chain that needs to be mocked if (response.headersSent ...