Home > Back-end >  Vue 3 Composition API using getters
Vue 3 Composition API using getters

Time:05-07

I'm refactoring some of my components using the composition API. I'm having problems with one component with asynchronous state trying to get data from one of it's getters.

The original component with 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);
    },
  },
};

As you can see nothing fancy here. I'm using namespaced vuex modules, passing parameters to a service etc. Now this is the refactored component using the composition api. I'm using the vuex-composition-helper. An important thing to notice is that incomingChats is coming from a websocket message hence is asynchronous. The original component code with the options API works perfect.

  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 the component template:

<template>
  <ul >
    <BaseChat
      v-for="(chat, index) in incomingChats"
      :key="index"
      :chat="chat"
      :
      @click="assigningChatToAgent(chat.id, chat)"
    />
  </ul>
</template>

What is happening with the composition API is that I'm getting this error:

Uncaught ReferenceError: Cannot access 'agentId' before initialization

The error refers to this line here:

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

That agentId.value is coming from the agentId getter, but I don't understand what I'm doing wrong here. Hope somebody can help.

CodePudding user response:

The variable from outer scope is shadowed, agentId is in temporal dead zone at the time when agentId.value is accessed. Even if it weren't, it would be undefined because it refers itself on initialization.

It should be:

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