Show the name of the person that opened the ticket

Hello everyone,

This is something that I just can’t wrap my head around, I would appreciate it a lot if you guys could help me.

I am currently creating an app that fetches tickets from another app, and then when you select one ticket to view it, a modal appears with the ticket information.

Now, I’ve got most of the information to show up, including all the conversations but I just cannot make the ticket creator’s name appear (it’s always “undefined”):
image

This is the code inside of the modal that I’m using to try and show the names:

First, function setNamesInConversations is called to inject the name inside the JSON object of the conversation:

async function setNamesInConversations(data) {
    data.forEach(async conversation => {
        let u_id = conversation.user_id
        let is_contact = false
        let name = ""
        let agent = await client.request.invokeTemplate("fdGetMethod", {
            context: {
                "path": `agents/${u_id}`
            }
        }).catch(() => is_contact = true)
        let contact = ""
        if (is_contact) {
            contact = await client.request.invokeTemplate("fdGetMethod", {
                context: {
                    "path": `contacts/${u_id}`
                }
            }).catch(() => console.log("Erro a encontrar a pessoa nos contactos."))
            name = JSON.parse(contact.response)["name"]
        } else {
            name = JSON.parse(agent.response)["contact"]["name"]
        }
        conversation.name = name
    })

    return data
}

Then, I dynamically create a header for the modal with HTML that contains ticket information:

async function showHeader(data) {
    const ticket = data.ticket
    let requester = data.requester
    const created_at = ticket.created_at
    const inputDate = new Date(created_at)
    const outputDateString = ('0' + inputDate.getUTCDate()).slice(-2) + '-' + ('0' + (inputDate.getUTCMonth() + 1)).slice(-2) + '-' + inputDate.getUTCFullYear() + ' ' + ('0' + inputDate.getUTCHours()).slice(-2) + ':' + ('0' + inputDate.getUTCMinutes()).slice(-2);
    if (requester.type == "support_agent") {
        requester = requester.contact
    }

    let content = document.getElementById("content")
    content.innerHTML += `
    <div class="ticketInfoCard">
        <div class="createdByInfo">
            <p class="dateP">${requester.name} (${requester.email}) | ${outputDateString}</p>
        </div>
        <h3>Ticket #${ticket.id}</h3>
        <h3>Assunto: ${ticket.subject}</h3>
        <p>${ticket.description}</p>
    </div>
    `

    content.innerHTML += `
        <div id="addMessage" class="addMessageDiv message">
            <div>
                <textarea id="noteText"></textarea>            
            </div>
            <button onclick="sendMessage(${ticket.id})">Criar nota</button>
        </div>
    `
    await setNamesInConversations(data.conversations).then((res) => showConversationBoxes(res, content))
}

Then I create a box for each conversation and dynamically populate the box with the conversation info:

function showConversationBoxes(conversations, content) {
    conversations = conversations.reverse()
    conversations.forEach(conversation => {
        const updated_at = conversation.updated_at
        const inputDate = new Date(updated_at)
        const outputDateString = ('0' + inputDate.getUTCDate()).slice(-2) + '-' + ('0' + (inputDate.getUTCMonth() + 1)).slice(-2) + '-' + inputDate.getUTCFullYear() + ' ' + ('0' + inputDate.getUTCHours()).slice(-2) + ':' + ('0' + inputDate.getUTCMinutes()).slice(-2);
        let cls = ""
        switch (conversation.category) {
            case 2:
                cls = "private-note"
                break
            case 3:
                cls = "reply"
                break
        }
        content.innerHTML += `
        <div class="message ${cls}">
            <div class="message-title">
                <p class="dateP">${outputDateString}</p>
                <p id="conversationName"><strong>${conversation.name}:</strong></p>
            </div>
            <p>${conversation.body}</p>
        </div>
        `
    });
}

The problem is, even though I am “awaiting” for the resolution of the conversations before trying to show them, the name is always undefined! It’s as if the execution continues before it sets the name.

Any help would be greatly appreciated, I’ve been trying to make this work for days without success.

Thank you

Hey @Jose_Cruz,

It sounds like a JavaScript problem rather than anything with our Freshworks platform. So, I pasted your entire question to ChatGPT and got this response. :slight_smile:

The issue you’re experiencing is due to the fact that forEach doesn’t work well with async/await. Even though await is used inside the forEach, it doesn’t wait for the async operations to complete before moving on to the next iteration. Instead, you can use a for...of loop, which handles async/await properly.

Then, I found this topic on StackOverflow, which confirmed the same.

Can you check if this updated function changed from forEach to for...of syntax works as expected?

async function setNamesInConversations(data) {
    for (const conversation of data) {
        let u_id = conversation.user_id;
        let is_contact = false;
        let name = "";
        try {
            let agent = await client.request.invokeTemplate("fdGetMethod", {
                context: {
                    "path": `agents/${u_id}`
                }
            });
            name = JSON.parse(agent.response)["contact"]["name"];
        } catch (error) {
            is_contact = true;
        }
        if (is_contact) {
            try {
                let contact = await client.request.invokeTemplate("fdGetMethod", {
                    context: {
                        "path": `contacts/${u_id}`
                    }
                });
                name = JSON.parse(contact.response)["name"];
            } catch (error) {
                console.log("Erro a encontrar a pessoa nos contactos.");
            }
        }
        conversation.name = name;
    }
    return data;
}

Please add some more logs at all the functions’ entry and exit points to see if the expected arguments and responses are received.

Hello @Raviraj !

That actually worked.
It’s as slow as a snail, execution takes around 20 seconds, but it sure works!

Thank you very much

1 Like

This topic was automatically closed 6 days after the last reply. New replies are no longer allowed.