Initializing Custom States

Hello good day is there a way for initializing custom states as I am having problems when checking against them.
I checked before and when I used an uninitialized custom state in an if statement it went to the else branch, but now it throws me an error and makes the chatflow respond with just a line.

Here is the source code:

 try {
 if (event.session.customState.customResponse != '') {
 requestMessage = event.session.customState.customResponse
 oldConversation = true

 } else if (event.session.customState.oldConversation == 'true') {
 requestMessage = event.userMessage.message
 oldConversation = true
 } else {
 requestMessage = 'Hello Good Day'
 oldConversation = true
 }
 } catch (error) {
 requestMessage = event.userMessage.message
 }

It currently gives an incorrect error when run

ERROR Invoke Error {"errorType":"TypeError","errorMessage":"Cannot read properties of undefined (reading 'toLowerCase')","stack":["TypeError: Cannot read properties of undefined (reading 'toLowerCase')"," at exports.main (/var/task/Template.js:57:24)"," at exports.hubspot_handler [as handler] (/var/task/hubspotHandler.js:7:21)"," at Runtime.handleOnceNonStreaming (file:///var/runtime/index.mjs:1187:29)"]}

This points to another line of code that runs after said comparison and assignment.

Thank you.

Hey @Igee :waving_hand: Thanks for the interesting question. I wonder if this is happening because at the very beginning of a conversation, `event.userMessage.message` can also be undefined, which leads to the error in a later part of the code. Have you tried to directly and explicitly check if your state and message exist? Also, an option to consider — using optional chaining `(?.)` to safely access nested properties like `event.session.customState.customResponse`, which prevents an error by immediately returning undefined if any object in the chain is missing.

Example:

if (event.session?.customState?.customResponse) { … }

Best,

Jaycee

This seems to work as a solution to my problem. The if statement goes to the false clause when the states are undefined now. Thank you.

 try {
 if (event.session.customState?.customResponse) {
 requestMessage = event.session.customState.customResponse
 oldConversation = true

 } else if (event.session.customState?.oldConversation) {
 requestMessage = event.userMessage.message
 oldConversation = true

 } else {
 requestMessage = 'Hello Good Day'
 oldConversation = true

 }

Hey, @Igee :waving_hand: Thank you so much for taking the time to come back and let us know what worked! — Jaycee