Manage State

Params are variables that are set within a conversation. But, whenever a session is reset or expires, these variables are lost.

Using a simple storage mechanism you can manage stateful data. Data is stored on a thread level and can be accessed even weeks after the first conversation took place.

Code example

async payload => {

  // Get the current count, or 0
  let count = await state.get('count') || 0

  // Save the current count
  await state.save('count', count + 1 )

  // Show or speak the current count
  return new Message(`Count is ${count}`)
}

Save a Value

Storing data can be done using the state.save() method. Provide a key and value to save:

async payload => {

  await state.save('watched', {
    season: 1,
    episode: 2,
    serie: 'game-of-thrones'
  })
}

Get a Value

Fetch a value by key using the get() method:

async payload => {

  // Could be null if not found
  const watched = await state.get('watched')

  if(watched) {
    // ....
  }
}

📘

Note

If no data exists get() will return null

Removing values

Remove a specific value by key:

async payload => {
  // Remove aa specific key
  await state.remove('watched')
}

Clear all values stored for this thread:

async payload => {
  // Remove all data for this conversation
  await state.clear()
}

Reference

state.save(key, value)

Save data in state

Returns: Promise - Promise that resolves with the value being stored

Properties

NameTypeDescription
keystringKey used to save data
valueobjectEither an object, array, or string to store

state.get(key)

Retrieve data from the state by key.

Returns: Promise - Promise that resolved with the value being stored or null if the key does not exist.

Properties

NameTypeDescription
KeystringKey used to find the data

state.remove(key)

Remove data from the state by key.

Returns: Promise - Resolves with the key of the deleted data

Properties

NameTypeDescription
KeystringKey of the data to delete

state.clear()

Clear all data from the state.

Returns: undefined