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

Updating a validation directive on $watch in AngularJS version 1.2

I created a directive for validation on a multi-select that allows for dynamic length validation of selected items. The directive is used like this: (function() { 'use strict'; angular .module('myModule') .dire ...

Can LocalStorage be deleted when the application is not running?

Can a specific key in an application's LocalStorage be deleted without having to open the app? I'm considering creating a batch file script for removing a particular key from the app's LocalStorage while the app is not running. The challeng ...

When I remove a user as admin, I am unable to retrieve all users to update the data table

I am currently working on an Admin Dashboard that includes a section for users. This section features a simple table displaying all the users in the MongoDB database along with some information. Additionally, there are functionalities to add a new user and ...

The putImageData function claims that the given object is not an ImageData object, but upon inspection in the console, it clearly displays that it is

After using getImageData to store the pixels of an image in a two-dimensional array, I attempted to draw them with putImageData. However, I encountered an error indicating that the first parameter is not of type ImageData. Strangely, when I logged the vari ...

The Node.js server seems to be continuously loading without producing any output

I've been struggling with getting my server to function properly. Whenever I send post data, the page just keeps loading and doesn't display any results. Here is a snippet of my Node.js file: var http = require('http'); var url = requi ...

What could be causing this code to malfunction on a mobile device?

I am struggling to make this drag and drop function work on mobile devices. Despite implementing the code, it doesn't seem to function properly when accessed on my mobile phones. Here is the snippet of the code: copy = 1; $('.dragArea img&apo ...

I tried utilizing the useState hook to store the value, but surprisingly, it failed to update

I am brand new to Reactjs and currently working on creating an address form that includes 3 select options for country, state, and city. I have implemented React hooks in my project, where the page fetches a list of countries upon initial load. Subsequentl ...

The autoIncrement feature is causing a syntax error at or near "SERIAL"

Encountering a build error : Unable to start server due to the following SequelizeDatabaseError: syntax error at or near "SERIAL" This issue arises only when using the autoIncrement=true parameter for the primary key. 'use strict'; export ...

Generating an array of objects based on a specified condition

I am working on creating an array of objects. I want to add objects based on a condition, but instead of not adding the object in the array, it is adding false. I have attempted the following: const flag = false; const list = [ { key: 'abc&a ...

Obtain the shared value between two data entries within a Vue array

In my Vue.js data, I have two records with the same question id. I want to select both record options and only one of the questions. [ { "id":7, "question_id":102, "option":"true", "is_corr ...

Could you assist me in retrieving information from an API request?

I can't seem to pinpoint my mistake, but I know it's there. After the user provides their state and city information and submits it, a fetch request is supposed to retrieve latitude and longitude values. These values are then used in another API ...

Once the "Get Route" button is pressed, I want to save my JavaScript variable into a database

I am seeking to automatically extract data from the Google Maps API and store it in my MySQL database. Specifically, I want details such as source address, destination address, distance, and duration for all available routes to be inserted into my database ...

Checking the validity of a username through regex

I have implemented a Username field validation in Vue using regex. A key down event triggers the method below with each keystroke: userNameValidation(event) { if (!event.key.match(/^[a-zA-Z0-9._]+$/)) { event.preventDefault(); } ...

Processing two Array Objects can be achieved without resorting to the EVAL function

I have two objects that I need to process. obj1 contains an array of objects with formulas. obj2 holds the values needed for the calculations. I am looking for a way to process and calculate both objects in order to obtain a result where the keys present ...

A method in JavaScript to fetch a single variable using the GET request

Although I am new to writing JavaScript, I am currently working on an iOS application that will make use of JavaScriptCore's framework to interpret a piece of javascript code in order to obtain a specific variable. My goal is to establish a GET reques ...

What is the best way to insert an <image> tag into the SVG DOM?

Currently, I am facing an issue with adding a background image to the generated SVG DOM in my web page. The user interacts by drawing an SVG doodle on top of a jpg image using Raphael. After the user is done with their drawing, I want to enable them to sa ...

Enhancing Next.js Images with Custom CSS Styles

I am working with a Next.js component: import styles from '../styles/Navbar.module.css' import Image from 'next/image' export const Navbar = () => { <div> <Image className={styles["navbar-home-icon"]} ...

Expanding the input focus to include the icon, allowing it to be clicked

Having trouble with my date picker component (v-date-picker) where I can't seem to get the icon, a Font Awesome Icon separate from the date-picker, to open the calendar on focus when clicked. I've attempted some solutions mentioned in this resour ...

JQuery may be successfully loaded, but it is not functioning as intended

Just started dabbling in JQuery (I'm a newbie) but I'm having trouble getting it to work! Initially, it worked a couple of times but then suddenly stopped working (pretty strange). I made some changes and now it doesn't work at all. JQuery a ...

Execute a specialized function with imported modules and specified parameters

Within an npm project, I am looking to execute a custom function with arguments, or ideally provide it as a script in the package.json file like this: npm run custom-function "Hello, World". Currently, I have a file called src/myFunction.ts: import * as e ...