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.