RSS

Blog posts tagged with 'scope'

Session Attributes

Introduction

Session attributes can be treated like special variables which you can use to store and retreive information across various intents.

Why is this important?

Variables declared inside your intents using 'var', 'const' or 'let' are scoped within those intents, meaning you can no longer call those variables once the intent is over.

Session attributes are global, meaning you can retreive their data from within any intent.

How do I use them?

The first recommended step is to get the sessionAttributes path using the following line:

const sessionAttributes = handlerInput.attributesManager.getSessionAttributes();

This line essentially just saves you from typing the entire path every time. The location it points to is where you can get existing session attributes, or make new ones.

Now you can make a new session attribute and set its value.

sessionAttributes.<VARIABLE NAME> = <VALUE HERE>;

e.g.

sessionAttributes.myVariable = "test string"; // remember this variable -- we will call it later!

This is similar to declaring a variable using 'var', 'const' or 'let'.

The value can be anything you want. You should set the value to be something which you want the skill to remember and use across various intents.

Finally, you need to set the session attributes which you have declared. Do so using this line of code:

handlerInput.attributesManager.setSessionAttributes(sessionAttributes);

This line always comes next, and is necessary for your session attributes to be saved.

To call sessionAttributes from within a different intent, you first need to get sessionAttributes again:

const sessionAttributes = handlerInput.attributesManager.getSessionAttributes();

Now you can recall any of your session attributes like this:

sessionAttributes.<VARIABLE NAME>

e.g.

sessionAttributes.myVariable

To test this, you could use console.log() to check the value of myVariable.

console.log(sessionAttributes.myVariable); // output: "test string"

Practical example

Get, then set.

const sessionAttributes = handlerInput.attributesManager.getSessionAttributes();

sessionAttributes.forename = "john";

sessionAttributes.surname = "smith";

sessionAttributes.favColour = "blue";

handlerInput.attributesManager.setSessionAttributes(sessionAttributes);

The next step is retreiving your session attributes from a different intent.

First, get the sessionAttributes.

const sessionAttributes = handlerInput.attributesManager.getSessionAttributes();

Now you can retreive your sessionAttributes like this:

console.log(sessionAttributes.forename); // output: "john"

console.log(sessionAttributes.surname); // output: "smith"

console.log(sessionAttributes.favColour); // output: "blue"

Further reading

https://developer.amazon.com/en-US/docs/alexa/custom-skills/manage-skill-session-and-session-attributes.html