Leveraging Vue 3 Composition API with accessors

I'm currently in the process of refactoring some of my components using the composition API. One component is giving me trouble, specifically with asynchronous state when trying to retrieve data from one of its getters.

Initially, the component was using the options API:

export default {
  computed: {
    ...mapGetters({
      incomingChats: "websocket/getIncomingChats",
      agentId: "token/getAgentId",
    }),
  },
  methods: {
    ...mapActions({
      addChatSession: "chatSession/addChatSession",
    }),
    assigningChatToAgent(chatId) {
      let agentId = JSON.parse(JSON.stringify(this.agentId));
      let assignChatObject = {
        aggregateId: chatId,
        agentId: agentId.agentId,
      };
      AssignChatService.assignChatToAgent(assignChatObject);
    },
  },
};

Now, after refactoring using the composition API and utilizing the vuex-composition-helper, I've encountered an issue. The incomingChats data is retrieved asynchronously through a websocket message. Despite the original component with the options API working fine, the refactored version throws an error.

setup() {
    const { incomingChats, agentId } = useGetters({
      incomingChats: "websocket/getIncomingChats",
      agentId: "token/getAgentId",
    });
    const { addChatSession } = useActions({
      addChatSession: "chatSession/addChatSession",
    });
    function assigningChatToAgent(chatId) {
      const agentId = JSON.parse(JSON.stringify(agentId.value));
      const assignChatObject = {
        aggregateId: chatId,
        agentId: agentId.agentId,
      };
      AssignChatService.assignChatToAgent(assignChatObject);
    }
    return {
      incomingChats,
      agentId,
      addChatSession,
      assigningChatToAgent,
    };
  },

This is how the component template looks now:

<template>
  <ul class="overflow-y-auto pr-2">
    <BaseChat
      v-for="(chat, index) in incomingChats"
      :key="index"
      :chat="chat"
      :class="{ 'mt-0': index === 0, 'mt-4': index > 0 }"
      @click="assigningChatToAgent(chat.id, chat)"
    />
  </ul>
</template>

The specific error message being shown is:

Uncaught ReferenceError: Cannot access 'agentId' before initialization

This error points to the line:

const agentId = JSON.parse(JSON.stringify(agentId.value));

The 'agentId.value' is obtained from the agentId getter, but I am unsure of what mistake I might be making here. Your assistance would be greatly appreciated.

Answer №1

The variable from the outer scope is being overshadowed, as agentId is currently in the temporal dead zone when attempting to access agentId.value. Even if it were accessible, it would still be undefined due to referring to itself during initialization.

A solution could look like this:

const agentIdValue = JSON.parse(JSON.stringify(agentId.value));

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

Repeated attempts to initiate ajax script failing to function

I am completely new to the world of Ajax, having just started learning about it a few days ago. Despite my lack of experience, I need to incorporate it into a form that I am creating for my employer. Unfortunately, I have been facing difficulties in getti ...

Unexpected Token E encountered in the Twitter stream.on function

I'm currently in the process of setting up a search button on my web application that will pull all Twitter tweets related to the search input using the streaming API. Below is my client-side code: <form class="navbar-form navbar-left" role="sear ...

"Exploring the process of integrating angular-xeditable into a MeanJS project

I recently attempted to install angular-xeditable from the link provided, but encountered issues while trying to reference the JavaScript files in layout.html after downloading it with bower. According to the documentation, these files should be added auto ...

Utilizing the power of Ionic Native with AngularJS 1 for Cordova SQLite Integration

I am interested in implementing DeepLinking in my hybrid application using ionic-native. Currently, I have a functioning project with an SQLite database that has been tested on both iOS and Android platforms. However, when I include ionic.native in my app ...

How to automatically select the first item in a populated dropdown list using Vue JS

My HTML select element is populated with options from a server, but when using v-model, it initially selects an empty option instead of the first one. I came across a solution on a post which suggests selecting the first option manually, but since the dat ...

What is the method for identifying which input field the user has chosen on a web page retrieved from a server?

I attempted the code below without achieving the desired outcome. Any assistance would be greatly appreciated. UIPasteboard *pb = [UIPasteboard generalPasteboard]; [pb setString:passwordName]; NSString *jScriptString; jScriptString = [NSString string ...

How to eliminate certain elements from the DOM in Angular 5

I'm facing a minor issue in my Angular/Typescript project that I can't seem to resolve. I am still new to these technologies and struggling with removing certain DOM elements. The content is auto-generated with specific CSS classes, and unfortuna ...

Unique Google Maps API V3 PEGMAN Customization

Can custom zoom controls and Pegman controls be styled with the same design? To add custom zoom controls, follow the instructions provided in this question's answer: <!DOCTYPE html> <html> <head> <meta name="viewport" cont ...

Tips for avoiding the 'ResizeObserver loop finished with unhandled notifications.' error when using React with mui/material/Table

This is our current code snippet: import Table from '@mui/material/Table'; import TableBody from '@mui/material/TableBody'; import TableCell from '@mui/material/TableCell'; import TableContainer from '@mui/material/TableC ...

Script in Javascript halting Internet Explorer's operation

I'm encountering a problem with Internet Explorer freezing due to the following code. This code is part of a project that focuses on handling student grades: var array1 = StudentGradeAreadHugeList(); var nextArrayItem = function() { var grade = ...

Is there a way to customize the animation for a button in material UI?

Trying to implement material UI in React and looking for a button that does not have the standard wave animation effect upon clicking, which you can see demonstrated here. Instead, I am searching for an animation that instantly fills the entire button wit ...

Eliminate any line breaks from the information retrieved from the node event process.stdin.on("data") function

I've been struggling to find a solution to this issue. No matter what approach I take, I can't seem to remove the new line character at the end of my string. Take a look at my code below. I attempted using str.replace() in an effort to eliminate ...

Adjust the color of input labels using jQuery validate

I have a form where I want to change the class of the input labels when a specific field fails validation. My goal is to add the 'error' class to the spans that are directly above any invalid form elements. Here is an example of my HTML structur ...

Angular - Navigate to Login Page post registration and display a confirmation message

As a newcomer to Angular, I am currently working on an Angular and Spring Boot application. So far, I have created components for user login and registration along with validation features. Now, my goal is to redirect the user to the login page upon succes ...

Assign a specific value to each object

Receiving data from the backend in a straightforward manner: this.archiveService.getRooms(team).subscribe( res => { this.form = res; this.form.forEach(el => { el.reservation.slice(-6).match(/.{1,2}/g).join('/'); }); }, ...

I encounter difficulties when retrieving data in Next.js

Within a Next.js project, there is code provided that retrieves data from an external API endpoint and then passes it as props to a component called Services. This Services component utilizes the received data to dynamically render different sections of th ...

Make changes to external CSS using HTML and JavaScript

Is it possible to dynamically change the value of a background in an external CSS file using JavaScript? Currently, all my pages are connected to a CSS file that controls the background for each page. I am attempting to modify the background by clicking a ...

What steps should I follow to track an event using Firebug?

When I examine the element, how can I discover all of the events that are attached to it? ...

Tips for dynamically resetting the dataTable

When I create a datatable and add rows dynamically based on the selected option, I encounter an issue where I need to reinitialize the dataTable every time the option is changed. To address this, I have placed the reinitialization code inside the $("#selec ...

When working with Node.JS, is it necessary to include 'event' if you include 'net' using the require statement?

As I examine the code, I notice that there is no instance of "require('event')" present. However, there is this piece of code: server.on('error', function (e) { if (e.code == 'EADDRINUSE') { console.log('Address in ...