@textile/hub > Users > watchInbox
Users.watchInbox() method
watchInbox watches the inbox for new mailbox events. Returns a listener of watch connectivity states.
Signature:
watchInbox(id: string, callback: (reply?: MailboxEvent, err?: Error) => void): grpc.Request;
Parameters
Parameter | Type | Description |
---|---|---|
id | string | the mailbox id |
callback | (reply?: MailboxEvent, err?: Error) => void | handles each new mailbox event |
Returns:
grpc.Request
listener. listener.close will stop watching.
Example 1
Listen and log all new inbox events
import { Users, MailboxEvent } from '@textile/hub'
const callback = async (reply?: MailboxEvent, err?: Error) => {
if (!reply || !reply.message) return console.log('no message')
console.log(reply.type)
}
async function example (users: Users) {
const mailboxID = await users.getMailboxID()
const closer = await users.watchInbox(mailboxID, callback)
return closer
}
Example 2
Decrypt a new message in local user's inbox sent by listener callback
import { Users, MailboxEvent, PrivateKey } from '@textile/hub'
const userID = PrivateKey.fromRandom()
const callback = async (reply?: MailboxEvent, err?: Error) => {
if (!reply || !reply.message) return console.log('no message')
const bodyBytes = await userID.decrypt(reply.message.body)
const decoder = new TextDecoder()
const body = decoder.decode(bodyBytes)
console.log(body)
}
// Requires userID already be authenticated to the Users API
async function startListener(users: Users) {
const mailboxID = await users.getMailboxID()
const closer = await users.watchInbox(mailboxID, callback)
}