Skip to main content
Version: 0.11

@devvit/public-api - v0.11.5-dev

Table of contents

Namespaces

Enumerations

Classes

Type Aliases

Variables

Functions

Type Aliases

AllIconName

Ƭ AllIconName: typeof ALL_ICON_NAMES[number]


AppInstall

Ƭ AppInstall: "AppInstall"

The event name for when your app is installed


AppInstallDefinition

Ƭ AppInstallDefinition: Object

Type declaration

NameType
eventAppInstall
onEventTriggerOnEventHandler<protos.AppInstall>

AppUpgrade

Ƭ AppUpgrade: "AppUpgrade"

The event name for when your app is upgraded


AppUpgradeDefinition

Ƭ AppUpgradeDefinition: Object

Type declaration

NameType
eventAppUpgrade
onEventTriggerOnEventHandler<protos.AppUpgrade>

AsyncError

Ƭ AsyncError: Object

Type declaration

NameType
detailsstring | null
messagestring

AsyncUseStateInitializer

Ƭ AsyncUseStateInitializer<S>: () => Promise<S>

Type parameters

Name
S

Type declaration

▸ (): Promise<S>

Returns

Promise<S>


AutomoderatorFilterComment

Ƭ AutomoderatorFilterComment: "AutomoderatorFilterComment"

The event name for when a comment is filtered by automoderator


AutomoderatorFilterPost

Ƭ AutomoderatorFilterPost: "AutomoderatorFilterPost"

The event name for when a post is filtered by automoderator


BaseContext

Ƭ BaseContext: Object

Type declaration

NameTypeDescription
appAccountIdstringThe ID of the current app's account Deprecated Use BaseContext.appName instead to get the app's username
appNamestringThe slug of the app that is running
appVersionstringThe version of the app that is running
commentId?stringThe ID of the current comment
debugContextDebugInfoMore useful things, but probably not for the average developer
postId?stringThe ID of the current post
subredditIdstringThe ID of the current subreddit
subredditName?stringThe name of the current subreddit
userId?stringThe current user's ID if this event was triggered by a logged in user
toJSON() => Omit<BaseContext, "toJSON">Returns a JSON representation of the context

BaseField

Ƭ BaseField<ValueType>: Object

Type parameters

Name
ValueType

Type declaration

NameTypeDescription
defaultValue?ValueTypeThe default value of the field
disabled?booleanIf true the field will be disabled
helpText?stringAn optional help text that will be displayed below the field
labelstringThe label of the field. This will be displayed to the user
namestringThe name of the field. This will be used as the key in the values object when the form is submitted.
required?booleanIf true the field will be required and the user will not be able to submit the form without filling it in.
scope?SettingScopeTypeThis indicates whether the field (setting) is an app level or install level setting. App setting values can be used by any installation.

BlockElement

Ƭ BlockElement: Object

Type declaration

NameType
childrenJSX.Element[]
props{ [key: string]: unknown; } | undefined
typeJSX.ComponentFunction | string | undefined

BooleanField

Ƭ BooleanField: Prettify<Omit<BaseField<boolean>, "required"> & FieldConfig_Boolean & { type: "boolean" }>

A boolean field displayed as a toggle


CancelJob

Ƭ CancelJob: (jobId: string) => Promise<void>

Cancel a scheduled job

Type declaration

▸ (jobId): Promise<void>

Parameters
NameTypeDescription
jobIdstringThe id of the job to cancel
Returns

Promise<void>


CommentCreate

Ƭ CommentCreate: "CommentCreate"

The event name for when a comment is created, after safety delay


CommentCreateDefinition

Ƭ CommentCreateDefinition: Object

Type declaration

NameType
eventCommentCreate
onEventTriggerOnEventHandler<protos.CommentCreate>

CommentDelete

Ƭ CommentDelete: "CommentDelete"

The event name for when a comment is deleted


CommentDeleteDefinition

Ƭ CommentDeleteDefinition: Object

Type declaration

NameType
eventCommentDelete
onEventTriggerOnEventHandler<protos.CommentDelete>

CommentReport

Ƭ CommentReport: "CommentReport"

The event name for when a comment is reported


CommentReportDefinition

Ƭ CommentReportDefinition: Object

Type declaration

NameType
eventCommentReport
onEventTriggerOnEventHandler<protos.CommentReport>

CommentSubmit

Ƭ CommentSubmit: "CommentSubmit"

The event name for when a comment is submitted


CommentSubmitDefinition

Ƭ CommentSubmitDefinition: Object

Type declaration

NameType
eventCommentSubmit
onEventTriggerOnEventHandler<protos.CommentSubmit>

CommentUpdate

Ƭ CommentUpdate: "CommentUpdate"

The event name for when a comment is updated


CommentUpdateDefinition

Ƭ CommentUpdateDefinition: Object

Type declaration

NameType
eventCommentUpdate
onEventTriggerOnEventHandler<protos.CommentUpdate>

Configuration

Ƭ Configuration: Object

Type declaration

NameTypeDescription
http?PluginSettings | booleanAllows your app to use the HTTP/Fetch API
kvStore?PluginSettings | booleanAllows your app to use the Key-Value Store
media?PluginSettings | booleanAllows media uploads from apps
modLog?PluginSettings | booleanAllows using ModLog API
realtime?PluginSettings | booleanAllows your app to use the Realtime Plugin
redditAPI?PluginSettings | booleanAllows your app to use the reddit API
redis?PluginSettings | booleanAllows your app to use the Redis Plugin

Context

Ƭ Context: ContextAPIClients & BaseContext

The current app context of the event or render


ContextAPIClients

Ƭ ContextAPIClients: Object

Type declaration

NameTypeDescription
assetsAssetsClientA client for resolving static assets to public URLs
cacheCacheHelperThe cache helper will let you cache JSON-able objects in your devvit apps for a limited amount of time. Under the covers, It's just Redis, so you do need to enable the redis feature. This provides a pattern for e.g. fetching remote calls without overwhelming someone's server. ts Devvit.configure({ redis: true, // Enable access to Redis }); /// ... let component = (context) => { let cached = context.cache(async () => { let rsp = await fetch("https://google.com") return rsp.body }, { key: "some-fetch", ttl: 10_000 // millis } doSomethingWith(cached); return <text>yay</text> }
dimensions?UIDimensionsInformation about about a custom post's layout. Will be undefined for non custom post surface areas such as menu items and task schedulers.
kvStoreKVStoreA client for the Key Value Store
mediaMediaPluginA client for media API
modLogModLogClientA client for the ModLog API
realtimeRealtimeClientA client for Realtime API
redditRedditAPIClientA client for the Reddit API
redisRedisClientA client for the Redis API
schedulerSchedulerA client for the Scheduler API
settingsSettingsClientA client for the Settings API
uiUIClientA client for the User Interface API
uiEnvironment?UIEnvironmentAdditional information about client environment. Will be undefined for non-ui contexts such as task schedulers or triggers.
useChannel<Message>(options: ChannelOptions<Message>) => UseChannelResult<Message>A hook for managing a realtime pubsub channel between Block renders. This is only available within a Block Component. Deprecated Using hooks from context is deprecated and will be removed in a future release. Import and use hooks directly from the public-api. ts // Old: const channel = context.useChannel(...); // New: import { useChannel } from '@devvit/public-api' const channel = useChannel(...);
useForm<T>(form: T, onSubmit: (values: FormToFormValues<T>) => void | Promise<void>) => FormKeyA hook for managing a form between Block renders. This is only available within a Block Component. Deprecated Using hooks from context is deprecated and will be removed in a future release. Import and use hooks directly from the public-api. ts // Old: const myForm = context.useForm(...); // New: import { useForm } from '@devvit/public-api' const myForm = useForm(...);
useIntervalUseIntervalHookA hook for managing a callback that runs on an interval between Block renders. This is only available within a Block Component. Deprecated Using hooks from context is deprecated and will be removed in a future release. Import and use hooks directly from the public-api. ts // Old: const interval = context.useInterval(() => {}, 1000); // New: import { useInterval } from '@devvit/public-api' const interval = useInterval(() => {}, 1000);
useState(initialState: boolean | () => boolean | Promise<boolean>) => UseStateResult<boolean>(initialState: number | () => number | Promise<number>) => UseStateResult<number>(initialState: string | () => string | Promise<string>) => UseStateResult<string><S>(initialState: S | () => S | Promise<S>) => UseStateResult<S>A hook for managing a state between Block renders. This is only available within a Block Component. Returns a tuple containing the current state and a function to update it. ts const [counter, setCounter] = useState(0); setCounter(1); // counter = 1 setCounter((count) => count + 1) // counter = 2 Deprecated Using hooks from context is deprecated and will be removed in a future release. Import and use hooks directly from the public-api. ts // Old: const [counter, setCounter] = context.useState(0); // New: import { useState } from '@devvit/public-api' const [counter, setCounter] = useState(0);

ContextDebugInfo

Ƭ ContextDebugInfo: { effects?: EffectEmitter ; metadata: Metadata } & { [key in AppDebug]?: string }


CustomPostType

Ƭ CustomPostType: Object

Type declaration

NameTypeDescription
description?stringA description of the custom post type
height?RootHeightThe fixed height of the post, defaults to 'regular'
namestringThe name of the custom post type
renderCustomPostComponentA function component that renders the custom post

Data

Ƭ Data: JSONObject

Deprecated

Use JSONObject instead.


DevvitDebug

Ƭ DevvitDebug: Object

Home for debug flags, settings, and other information. Any type removals may cause type errors but not runtime errors.

Favor ContextDebugInfo since request-based state is preferred.

Type declaration

NameTypeDescription
emitSnapshots?booleanShould debug block rendering in console.log according to the reified JSX/XML output. Example: hi world
emitState?booleanShould console.log the state of the app after every event.

Dispatch

Ƭ Dispatch<A>: (value: A) => void

Type parameters

Name
A

Type declaration

▸ (value): void

Parameters
NameType
valueA
Returns

void


Form

Ƭ Form: Object

Type declaration

NameTypeDescription
acceptLabel?stringAn optional label for the submit button
cancelLabel?stringAn optional label for the cancel button
description?stringAn optional description for the form
fieldsreadonly FormField[]The fields that will be displayed in the form
title?stringAn optional title for the form

FormDefinition

Ƭ FormDefinition<T>: Object

Type parameters

NameType
Textends Form | FormFunction = Form | FormFunction

Type declaration

NameTypeDescription
formTA form or a function that returns a form
onSubmitFormOnSubmitEventHandler<FormToFormValues<T>>A callback that will be invoked when the form is submitted

FormField

Ƭ FormField: StringField | ImageField | ParagraphField | NumberField | BooleanField | SelectField | FormFieldGroup


FormFieldGroup

Ƭ FormFieldGroup: Object

A grouping of fields

Type declaration

NameTypeDescription
fieldsreadonly FormField[]The fields that will be displayed in the group
helpText?stringAn optional help text that will be displayed below the group
labelstringThe label of the group that will be displayed to the user
required?never-
type"group"-

FormFunction

Ƭ FormFunction<T>: (data: T) => Form

A function that returns a form. You can use this to dynamically generate a form.

Example

const formKey = Devvit.createForm((data) => ({
fields: data.fields,
title: data.title,
}), callback);

...

ui.showForm(formKey, {
fields: [{ type: 'string', name: 'title', label: 'Title' }]
title: 'My dynamic form'
});

Type parameters

NameType
Textends Object = { [key: string]: any; }

Type declaration

▸ (data): Form

Parameters
NameType
dataT
Returns

Form


FormKey

Ƭ FormKey: `form.${number}` | `form.hook.${string}.${number}`

A unique key generated by Devvit.createForm or the useForm hook.


FormOnSubmitEvent

Ƭ FormOnSubmitEvent<T>: Object

Type parameters

NameType
Textends Partial<JSONObject>

Type declaration

NameTypeDescription
valuesTThe form values that were submitted

FormOnSubmitEventHandler

Ƭ FormOnSubmitEventHandler<Data>: (event: FormOnSubmitEvent<Data>, context: Context) => void | Promise<void>

Type parameters

NameType
Dataextends Partial<JSONObject>

Type declaration

▸ (event, context): void | Promise<void>

Parameters
NameType
eventFormOnSubmitEvent<Data>
contextContext
Returns

void | Promise<void>


FormToFormValues

Ƭ FormToFormValues<T>: FormFieldsToFormValues<T extends FormFunction ? ReturnType<T> : T["fields"]>

Type parameters

NameType
Textends Form | FormFunction = Form | FormFunction

FormValues

Ƭ FormValues: JSONObject


IconName

Ƭ IconName: `${AllIconName}` | `${AllIconName}-outline` | `${AllIconName}-fill`


ImageField

Ƭ ImageField: Omit<BaseField<string>, "defaultValue"> & { type: "image" }

Allows a user to upload an image as part of submitting the form. The string value that's given back is the URL of the image.


JSONArray

Ƭ JSONArray: JSONValue[]


JSONObject

Ƭ JSONObject: Object

Index signature

▪ [key: string]: JSONValue


JSONPrimitive

Ƭ JSONPrimitive: boolean | null | number | string


JSONValue

Ƭ JSONValue: JSONPrimitive | JSONArray | JSONObject

Any JSON type. Ie, a string, number, boolean, null, an array of these JSON types, or an object with JSON type values, recursively.

This type is often used to type-check attempts to serialize and deserialize classes, functions, and other JavaScript-only types that cannot be represented losslessly in plain JSON.

See


JobContext

Ƭ JobContext: Omit<Context, "ui" | "dimensions" | "modLog" | "uiEnvironment">


KVStore

Ƭ KVStore: Object

Type declaration

NameType
delete(key: string) => Promise<void>
get<T>(key: string) => Promise<undefined | T>
list() => Promise<string[]>
put(key: string, value: JSONValue) => Promise<void>

MediaAsset

Ƭ MediaAsset: Object

Type declaration

NameType
mediaIdstring
mediaUrlstring

MediaPlugin

Ƭ MediaPlugin: Object

Type declaration

NameType
upload(opts: UploadMediaOptions) => Promise<MediaAsset>

MenuItem

Ƭ MenuItem: Object

Type declaration

NameTypeDescription
description?stringAn optional description for the menu item
forUserType?MenuItemUserType | MenuItemUserType[]The user type(s) that the menu item should be displayed for
labelstringThe label of the menu item
locationMenuItemLocation | MenuItemLocation[]The location(s) where the menu item should be displayed
onPress(event: MenuItemOnPressEvent, context: Context) => void | Promise<void>A function that is called when the menu item is pressed
postFilter?MenuItemPostFilterThe filter that applies to post menu items and has no effect on non-post actions

MenuItemLocation

Ƭ MenuItemLocation: "subreddit" | "post" | "comment"


MenuItemOnPressEvent

Ƭ MenuItemOnPressEvent: Object

Type declaration

NameTypeDescription
locationMenuItemLocationThe location where the menu item was pressed
targetIdstringThe ID of subreddit, post, or comment that the menu item was pressed; includes Thing ID prefix: - t1* - comment - t5* - subreddit - t3_ - post

MenuItemPostFilter

Ƭ MenuItemPostFilter: "currentApp"

You can use the "currentApp" filter to only display the menu item on custom posts that were created by your app.


MenuItemUserType

Ƭ MenuItemUserType: "loggedOut" | "moderator"


ModActionDefinition

Ƭ ModActionDefinition: Object

Type declaration

NameType
eventModActionTrigger
onEventTriggerOnEventHandler<protos.ModAction>

ModActionTrigger

Ƭ ModActionTrigger: "ModAction"

The event name for when a moderator action is recorded to a subreddit's modlog


ModMailDefinition

Ƭ ModMailDefinition: Object

Type declaration

NameType
eventModMailTrigger
onEventTriggerOnEventHandler<protos.ModMail>

ModMailTrigger

Ƭ ModMailTrigger: "ModMail"

The event name for when a mod mail is sent/received


MultiTriggerDefinition

Ƭ MultiTriggerDefinition<Event>: Object

Type parameters

NameType
Eventextends TriggerEvent

Type declaration

NameType
eventsreadonly Event[]
onEventTriggerOnEventHandler<TriggerEventType[Event]>

NumberField

Ƭ NumberField: Prettify<BaseField<number> & Omit<FieldConfig_Number, "min" | "max" | "step"> & { type: "number" }>

A number field


OnAutomoderatorFilterCommentDefinition

Ƭ OnAutomoderatorFilterCommentDefinition: Object

Type declaration

NameType
eventAutomoderatorFilterComment
onEventTriggerOnEventHandler<protos.AutomoderatorFilterComment>

OnAutomoderatorFilterPostDefinition

Ƭ OnAutomoderatorFilterPostDefinition: Object

Type declaration

NameType
eventAutomoderatorFilterPost
onEventTriggerOnEventHandler<protos.AutomoderatorFilterPost>

OnTriggerRequest

Ƭ OnTriggerRequest: protos.PostFlairUpdate | protos.PostSubmit | protos.PostCreate | protos.PostUpdate | protos.PostReport | protos.PostDelete | protos.CommentSubmit | protos.CommentCreate | protos.CommentUpdate | protos.CommentReport | protos.CommentDelete | protos.AppInstall | protos.AppUpgrade | protos.ModAction | protos.ModMail | protos.PostNsfwUpdate | protos.PostSpoilerUpdate | protos.AutomoderatorFilterPost | protos.AutomoderatorFilterComment


OnValidateHandler

Ƭ OnValidateHandler<ValueType>: (event: SettingsFormFieldValidatorEvent<ValueType>, context: Context) => void | string | Promise<void | string>

Type parameters

Name
ValueType

Type declaration

▸ (event, context): void | string | Promise<void | string>

Parameters
NameType
eventSettingsFormFieldValidatorEvent<ValueType>
contextContext
Returns

void | string | Promise<void | string>


ParagraphField

Ƭ ParagraphField: Prettify<BaseField<string> & Omit<FieldConfig_Paragraph, "maxCharacters"> & { type: "paragraph" }>

A paragraph or textarea field


PartialJSONArray

Ƭ PartialJSONArray: PartialJSONValue[]


PartialJSONObject

Ƭ PartialJSONObject: Partial<{ [key: string]: PartialJSONValue; }>


PartialJSONPrimitive

Ƭ PartialJSONPrimitive: boolean | null | number | string | undefined


PartialJSONValue

Ƭ PartialJSONValue: PartialJSONPrimitive | PartialJSONArray | PartialJSONObject

Like JSONValue but deeply allow lossy undefined values that are easier to type but may de/serialize differently or incorrectly. For example:

  • JSON.stringify({a: 1, b: 2, c: undefined, d: 3}): '{"a":1,"b":2,"d":3}'.
  • JSON.stringify([1, 2, undefined, 3]): '[1,2,null,3]'.
  • JSON.stringify(undefined): undefined.

JSON.stringify() accepts an any input so there are no typing guards. Prefer plain JSONValue when possible.

One mostly only cares about stringify since creating a JSON string with undefineds in it would require deliberate effort. These all throw errors:

  • JSON.parse('{a: 1, b: 2, c: undefined, d: 3}').
  • JSON.parse('[1, 2, undefined, 3]').
  • JSON.parse('undefined').
  • JSON.parse(undefined) (also a typing error).

PluginSettings

Ƭ PluginSettings: Object

Type declaration

NameTypeDescription
enabledbooleanWhether the plugin is enabled

PostCreate

Ƭ PostCreate: "PostCreate"

The event name for when a post is created, after safety delay


PostCreateDefinition

Ƭ PostCreateDefinition: Object

Type declaration

NameType
eventPostCreate
onEventTriggerOnEventHandler<protos.PostCreate>

PostDelete

Ƭ PostDelete: "PostDelete"

The event name for when a post is deleted


PostDeleteDefinition

Ƭ PostDeleteDefinition: Object

Type declaration

NameType
eventPostDelete
onEventTriggerOnEventHandler<protos.PostDelete>

PostFlairUpdate

Ƭ PostFlairUpdate: "PostFlairUpdate"

The event name for when the flair of a post is updated


PostFlairUpdateDefinition

Ƭ PostFlairUpdateDefinition: Object

Type declaration

NameType
eventPostFlairUpdate
onEventTriggerOnEventHandler<protos.PostFlairUpdate>

PostNsfwUpdate

Ƭ PostNsfwUpdate: "PostNsfwUpdate"

The event name for when a post is marked/unmarked as nsfw


PostNsfwUpdateDefinition

Ƭ PostNsfwUpdateDefinition: Object

Type declaration

NameType
eventPostNsfwUpdate
onEventTriggerOnEventHandler<protos.PostNsfwUpdate>

PostReport

Ƭ PostReport: "PostReport"

The event name for when a post is reported


PostReportDefinition

Ƭ PostReportDefinition: Object

Type declaration

NameType
eventPostReport
onEventTriggerOnEventHandler<protos.PostReport>

PostSpoilerUpdate

Ƭ PostSpoilerUpdate: "PostSpoilerUpdate"

The event name for when a post is marked/unmarked as spoiler


PostSpoilerUpdateDefinition

Ƭ PostSpoilerUpdateDefinition: Object

Type declaration

NameType
eventPostSpoilerUpdate
onEventTriggerOnEventHandler<protos.PostSpoilerUpdate>

PostSubmit

Ƭ PostSubmit: "PostSubmit"

The event name for when a post is submitted


PostSubmitDefinition

Ƭ PostSubmitDefinition: Object

Type declaration

NameType
eventPostSubmit
onEventTriggerOnEventHandler<protos.PostSubmit>

PostUpdate

Ƭ PostUpdate: "PostUpdate"

The event name for when a post is updated


PostUpdateDefinition

Ƭ PostUpdateDefinition: Object

Type declaration

NameType
eventPostUpdate
onEventTriggerOnEventHandler<protos.PostUpdate>

RedisClient

Ƭ RedisClient: Object

Type declaration

NameTypeDescription
globalOmit<RedisClient, "global">Allows read/write operations to global keys in Redis Global redis enables apps to persist and access state across subreddit installations
del(...keys: string[]) => Promise<void>Removes the specified keys. A key is ignored if it does not exist. https://redis.io/commands/del/ Arg keys Example ts async function delExample(context: Devvit.Context) { await context.redis.set("quantity", "5"); await context.redis.del("quantity"); }
expire(key: string, seconds: number) => Promise<void>Set a timeout on key. https://redis.io/commands/expire/ Arg key Arg seconds Example ts async function expireExample(context: Devvit.Context) { await context.redis.set("product", "milk"); await context.redis.expire("product", 60); // Set the product to expire in 60 seconds }
expireTime(key: string) => Promise<number>Returns the absolute Unix timestamp in seconds at which the given key will expire https://redis.io/commands/expiretime/ Arg key Example ts async function expireTimeExample(context: Devvit.Context) { await context.redis.set("product", "milk"); const expireTime : number = await context.redis.expireTime("product"); console.log("Expire time: " + expireTime); }
get(key: string) => Promise<undefined | string>Get the value of key. If the key does not exist the special value nil is returned. https://redis.io/commands/get/ Arg key Example ts async function getExample(context: Devvit.Context) { await context.redis.set("quantity", "5"); const quantity : string | undefined = await context.redis.get("quantity"); console.log("Quantity: " + quantity); }
getRange(key: string, start: number, end: number) => Promise<string>Returns the substring of the string value stored at key, determined by the offsets start and end (both are inclusive). https://redis.io/commands/getrange/ Arg key Arg start Arg end Example ts async function getRangeExample(context: Devvit.Context) { await context.redis.set("word", "tacocat"); const range : string = await context.redis.getRange("word", 0, 3) console.log("Range from index 0 to 3: " + range); }
hDel(key: string, fields: string[]) => Promise<number>Removes the specified fields from the hash stored at key. https://redis.io/commands/hdel/ Arg key Arg fields Example ts async function hDelExample(context: Devvit.Context) { await context.redis.hSet("fruits", {"apple": "5", "orange": "7", "kiwi": "9"}); const numFieldsRemoved = await context.redis.hDel("fruits", ["apple", "kiwi"]); console.log("Number of fields removed: " + numFieldsRemoved); }
hGet(key: string, field: string) => Promise<undefined | string>Returns the value associated with field in the hash stored at key. https://redis.io/commands/hget Arg key Arg field Example ts async function hGetExample(context: Devvit.Context) { await context.redis.hSet("fruits", {"apple": "5", "orange": "7", "kiwi": "9"}); const result : string | undefined = await context.redis.hGet("fruits", "orange"); console.log("Value of orange: " + result); }
hGetAll(key: string) => Promise<Record<string, string>>Returns all fields and values of the hash stored at key https://redis.io/commands/hgetall Arg key Example async function hGetAllExample(context: Devvit.Context) { await context.redis.hSet("groceryList", { "eggs": "12", "apples": "3", "milk": "1" }); const record : Record<string, string> = await context.redis.hGetAll("groceryList"); if (record.eggs !== undefined) { console.log(`Eggs: ${record.eggs}`); } }
hIncrBy(key: string, field: string, value: number) => Promise<number>Increments the number stored at field in the hash stored at key by increment. https://redis.io/commands/hincrby/ Arg key Arg field Arg value Example ts async function hIncrByExample(context: Devvit.Context) { await context.redis.hSet("user123", { "karma": "100" }); await context.redis.hIncrBy("user123", "karma", 5); }
hKeys(key: string) => Promise<string[]>Returns all field names in the hash stored at key. Arg key Example ts async function hKeysExample(context: Devvit.Context) { await context.redis.hSet("prices", { "chair": "48", "desk": "95", "whiteboard": "23" }); const keys : string[] = await context.redis.hKeys("prices"); console.log("Keys: " + keys); }
hLen(key: string) => Promise<number>Returns the number of fields contained in the hash stored at key. Arg key Example ts async function hLenExample(context: Devvit.Context) { await context.redis.hSet("supplies", { "paperclips": "25", "pencils": "10", "erasers": "5", "pens": "7" }); const numberOfFields : number = await context.redis.hLen("supplies"); console.log("Number of fields: " + numberOfFields); }
hMGet(key: string, fields: string[]) => Promise<(null | string)[]>Returns the values associated with fields in the hash stored at key. https://redis.io/commands/hmget Arg key Arg fields Example ts async function hMGetExample(context: Devvit.Context) { await context.redis.hSet("fruits", {"apple": "5", "orange": "7", "kiwi": "9"}); const result : string[] | undefined = await context.redis.hMGet("fruits", ["orange", "grape", "apple"]); console.log("Value of fields: " + result); // "Value of fields: ["7", undefined, "5"] }
hScan(key: string, cursor: number, pattern?: string, count?: number) => Promise<HScanResponse>Iterates fields of Hash types and their associated values. Arg key Arg cursor Arg pattern Arg count Example ts async function hScanExample(context: Devvit.Context) { await context.redis.hSet("userInfo", { "name": "Bob", "startDate": "01-05-20", "totalAwards": "12" }); const hScanResponse = await context.redis.hScan("userInfo", 0); hScanResponse.fieldValues.forEach(x => { console.log("Field: '" + x.field + "', Value: '" + x.value + "'"); }); }
hSet(key: string, fieldValues: { [field: string]: string; }) => Promise<number>Sets the specified fields to their respective values in the hash stored at key. https://redis.io/commands/hset Arg key Arg fieldValues Example ts async function hSetExample(context: Devvit.Context) { const numFieldsAdded = await context.redis.hSet("fruits", {"apple": "5", "orange": "7", "kiwi": "9"}); console.log("Number of fields added: " + numFieldsAdded); }
hdel(key: string, fields: string[]) => Promise<number>Removes the specified fields from the hash stored at key. https://redis.io/commands/hdel/ Deprecated Use RedisClient.hDel instead. Arg key Arg fields
hget(key: string, field: string) => Promise<undefined | string>Returns the value associated with field in the hash stored at key. https://redis.io/commands/hget Deprecated Use RedisClient.hGet instead. Arg key Arg field
hgetall(key: string) => Promise<Record<string, string>>Returns all fields and values of the hash stored at key https://redis.io/commands/hgetall Deprecated Use RedisClient.hGetAll instead. Arg key
hincrby(key: string, field: string, value: number) => Promise<number>Increments the number stored at field in the hash stored at key by increment. https://redis.io/commands/hincrby/ Deprecated Use RedisClient.hIncrBy instead. Arg key Arg field Arg value
hkeys(key: string) => Promise<string[]>Returns all field names in the hash stored at key. Deprecated Use RedisClient.hKeys instead. Arg key
hlen(key: string) => Promise<number>Returns the number of fields contained in the hash stored at key. Deprecated Use RedisClient.hLen instead. Arg key
hscan(key: string, cursor: number, pattern?: string, count?: number) => Promise<HScanResponse>Iterates fields of Hash types and their associated values. Deprecated Use RedisClient.hScan instead. Arg key Arg cursor Arg pattern Arg count
hset(key: string, fieldValues: { [field: string]: string; }) => Promise<number>Sets the specified fields to their respective values in the hash stored at key. https://redis.io/commands/hset Deprecated Use RedisClient.hSet instead. Arg key Arg fieldValues
incrBy(key: string, value: number) => Promise<number>Increments the number stored at key by increment. https://redis.io/commands/incrby/ Arg key Arg value Example ts async function incrByExample(context: Devvit.Context) { await context.redis.set("totalPoints", "53") const updatedPoints : number = await context.redis.incrBy("totalPoints", 100); console.log("Updated points: " + updatedPoints); }
mGet(keys: string[]) => Promise<(null | string)[]>Returns the values of all specified keys. https://redis.io/commands/mget/ Arg keys Example ts async function mGetExample(context: Devvit.Context) { await context.redis.mSet({"name": "Zeek", "occupation": "Developer"}); const result : (string | null)[] = await context.redis.mGet(["name", "occupation"]); result.forEach(x => { console.log(x); }); }
mSet(keyValues: { [key: string]: string; }) => Promise<void>Sets the given keys to their respective values. https://redis.io/commands/mset/ Arg keyValues Example ts async function mSetExample(context: Devvit.Context) { await context.redis.mSet({"name": "Zeek", "occupation": "Developer"}); }
mget(keys: string[]) => Promise<(null | string)[]>Returns the values of all specified keys. https://redis.io/commands/mget/ Deprecated Use RedisClient.mGet instead. Arg keys
mset(keyValues: { [key: string]: string; }) => Promise<void>Sets the given keys to their respective values. https://redis.io/commands/mset/ Deprecated Use RedisClient.mSet instead. Arg keyValues
set(key: string, value: string, options?: SetOptions) => Promise<string>Set key to hold the string value. If key already holds a value, it is overwritten https://redis.io/commands/set/ Arg key Arg value Arg options Example ts async function setExample(context: Devvit.Context) { await context.redis.set("quantity", "5"); }
setRange(key: string, offset: number, value: string) => Promise<number>Overwrites part of the string stored at key, starting at the specified offset, for the entire length of value. https://redis.io/commands/setrange/ Arg key Arg offset Example ts async function setRangeExample(context: Devvit.Context) { await context.redis.set("word", "tacocat"); await context.redis.setRange("word", 0, "blue"); }
strLen(key: string) => Promise<number>Returns the length of the string value stored at key. An error is returned when key holds a non-string value. https://redis.io/commands/strlen/ Arg key Example ts async function strLenExample(context: Devvit.Context) { await context.redis.set("word", "tacocat"); const length : number = await context.redis.strLen("word"); console.log("Length of word: " + length); }
strlen(key: string) => Promise<number>Returns the length of the string value stored at key. An error is returned when key holds a non-string value. https://redis.io/commands/strlen/ Deprecated Use RedisClient.strLen instead. Arg key
type(key: string) => Promise<string>Returns the string representation of the type of the value stored at key https://redis.io/commands/type/ Arg key Example ts async function typeExample(context: Devvit.Context) { await context.redis.set("quantity", "5"); const type : string = await context.redis.type("quantity"); console.log("Key type: " + type); }
watch(...keys: string[]) => Promise<TxClientLike>Marks the given keys to be watched for conditional execution of a transaction. https://redis.io/commands/watch/ Arg keys - given keys to be watched Example ts async function watchExample(context: Devvit.Context) { await context.redis.set("karma", "32"); const txn = await context.redis.watch("quantity"); await txn.multi(); // Begin a transaction await txn.incrBy("karma", 10); await txn.exec(); // Execute the commands in the transaction }
zAdd(key: string, ...members: ZMember[]) => Promise<number>Adds all the specified members with the specified scores to the sorted set stored at key. https://redis.io/commands/zadd/ Arg key Example ts async function zAddExample(context: Devvit.Context) { const numMembersAdded : number = await context.redis.zAdd("leaderboard", {member: "louis", score: 37}, {member: "fernando", score: 10}, {member: "caesar", score: 20}, {member: "alexander", score: 25}, ); console.log("Number of members added: " + numMembersAdded); }
zCard(key: string) => Promise<number>Returns the cardinality (number of elements) of the sorted set stored at key. https://redis.io/commands/zcard/ Arg key Example ts async function zCardExample(context: Devvit.Context) { await context.redis.zAdd("leaderboard", {member: "louis", score: 37}, {member: "fernando", score: 10}, {member: "caesar", score: 20}, {member: "alexander", score: 25}, ); const cardinality : number = await context.redis.zCard("leaderboard"); console.log("Cardinality: " + cardinality); }
zIncrBy(key: string, member: string, value: number) => Promise<number>Increments the score of member in the sorted set stored at key by value https://redis.io/commands/zincrby/ Arg key Arg member Arg value Example ts async function zIncrByExample(context: Devvit.Context) { await context.redis.zAdd("animals", {member: "zebra", score: 92}, {member: "cat", score: 100}, {member: "dog", score: 95}, {member: "elephant", score: 97} ); const updatedScore : number = await context.redis.zIncrBy("animals", "dog", 10); console.log("Dog's updated score: " + updatedScore); }
zRange(key: string, start: string | number, stop: string | number, options?: ZRangeOptions) => Promise<{ member: string ; score: number }[]>Returns the specified range of elements in the sorted set stored at key. https://redis.io/commands/zrange/ When using by: 'lex', the start and stop inputs will be prepended with [ by default, unless they already begin with [, ( or are one of the special values + or -. Arg key Arg start Arg stop Arg options Example ts async function zRangeExample(context: Devvit.Context) { await context.redis.zAdd("leaderboard", {member: "louis", score: 37}, {member: "fernando", score: 10}, {member: "caesar", score: 20}, {member: "alexander", score: 25}, ); // View elements with scores between 0 and 30 inclusive, sorted by score const scores : {member : string, score : number}[] = await context.redis.zRange("leaderboard", 0, 30, { by: "score" }); scores.forEach(x => { console.log("Member: " + x.member, ", Score: " + x.score); }); }
zRank(key: string, member: string) => Promise<undefined | number>Returns the rank of member in the sorted set stored at key https://redis.io/commands/zrank/ Arg key Arg member Example ts async function zRankExample(context: Devvit.Context) { await context.redis.zAdd("animals", {member: "zebra", score: 92}, {member: "cat", score: 100}, {member: "dog", score: 95}, {member: "elephant", score: 97} ); const rank : number | undefined = await context.redis.zRank("animals", "dog"); if(rank !== undefined) { console.log("Dog's rank: " + rank); } }
zRem(key: string, members: string[]) => Promise<number>Removes the specified members from the sorted set stored at key. https://redis.io/commands/zrem/ Arg key Arg members Example ts async function zRemExample(context: Devvit.Context) { await context.redis.zAdd("leaderboard", {member: "louis", score: 37}, {member: "fernando", score: 10}, {member: "caesar", score: 20}, {member: "alexander", score: 25}, ); const numberOfMembersRemoved : number = await context.redis.zRem("leaderboard", ["fernando", "alexander"]); console.log("Number of members removed: " + numberOfMembersRemoved); }
zRemRangeByLex(key: string, min: string, max: string) => Promise<number>removes all elements in the sorted set stored at key between the lexicographical range specified by min and max https://redis.io/commands/zremrangebylex/ Arg key Arg min Arg max Example ts async function zRemRangeByLexExample(context: Devvit.Context) { await context.redis.zAdd("fruits", {member: "kiwi", score: 0}, {member: "mango", score: 0}, {member: "banana", score: 0}, {member: "orange", score: 0}, {member: "apple", score: 0}, ); // Remove fruits alphabetically ordered between 'kiwi' inclusive and 'orange' exclusive // Note: The symbols '[' and '(' indicate inclusive or exclusive, respectively. These must be included in the call to zRemRangeByLex(). const numFieldsRemoved : number = await context.redis.zRemRangeByLex("fruits", "[kiwi", "(orange"); console.log("Number of fields removed: " + numFieldsRemoved); }
zRemRangeByRank(key: string, start: number, stop: number) => Promise<number>Removes all elements in the sorted set stored at key with rank between start and stop. https://redis.io/commands/zremrangebyrank/ Arg key Arg start Arg stop Example async function zRemRangeByRankExample(context: Devvit.Context) { await context.redis.zAdd("fruits", {member: "kiwi", score: 10}, {member: "mango", score: 20}, {member: "banana", score: 30}, {member: "orange", score: 40}, {member: "apple", score: 50}, ); // Remove fruits ranked 1 through 3 inclusive const numFieldsRemoved : number = await context.redis.zRemRangeByRank("fruits", 1, 3); console.log("Number of fields removed: " + numFieldsRemoved); }
zRemRangeByScore(key: string, min: number, max: number) => Promise<number>Removes all elements in the sorted set stored at key with a score between min and max https://redis.io/commands/zremrangebyscore/ Arg key Arg min Arg max Example ts async function zRemRangeByScoreExample(context: Devvit.Context) { await context.redis.zAdd("fruits", {member: "kiwi", score: 10}, {member: "mango", score: 20}, {member: "banana", score: 30}, {member: "orange", score: 40}, {member: "apple", score: 50}, ); // Remove fruits scored between 30 and 50 inclusive const numFieldsRemoved : number = await context.redis.zRemRangeByScore("fruits", 30, 50); console.log("Number of fields removed: " + numFieldsRemoved); }
zScan(key: string, cursor: number, pattern?: string, count?: number) => Promise<ZScanResponse>Iterates elements of Sorted Set types and their associated scores. Arg key Arg cursor Arg pattern Arg count Example ts async function zScanExample(context: Devvit.Context) { await context.redis.zAdd("fruits", {member: "kiwi", score: 0}, {member: "mango", score: 0}, {member: "banana", score: 0}, {member: "orange", score: 0}, {member: "apple", score: 0}, ); const zScanResponse = await context.redis.zScan("fruits", 0); console.log("zScanResponse: " + JSON.stringify(zScanResponse)); }
zScore(key: string, member: string) => Promise<undefined | number>Returns the score of member in the sorted set at key. https://redis.io/commands/zscore/ Arg key Arg member Example ts async function zScoreExample(context: Devvit.Context) { await context.redis.zAdd("leaderboard", {member: "louis", score: 37}, {member: "fernando", score: 10}, {member: "caesar", score: 20}, {member: "alexander", score: 25}, ); const score : number = await context.redis.zScore("leaderboard", "caesar"); console.log("Caesar's score: " + score); }

RunJob

Ƭ RunJob<Data>: (job: ScheduledJobOptions<Data> | ScheduledCronJobOptions<Data>) => Promise<string>

Schedule a new job to run at a specific time or on a cron schedule

Type parameters

NameType
Dataextends JSONObject | undefined

Type declaration

▸ (job): Promise<string>

Parameters
NameTypeDescription
jobScheduledJobOptions<Data> | ScheduledCronJobOptions<Data>The job to schedule
Returns

Promise<string>


ScheduledCronJob

Ƭ ScheduledCronJob: Object

Type declaration

NameTypeDescription
cronstringThe cron string of when this job should run
data?JSONObjectAdditional data passed in by the scheduler client
idstringID of the scheduled job. Use this with scheduler.cancelJob to cancel the job.
namestringThe name of the scheduled job type

ScheduledCronJobOptions

Ƭ ScheduledCronJobOptions<T>: Object

Type parameters

NameType
Textends JSONObject | undefined = JSONObject | undefined

Type declaration

NameTypeDescription
cronstringThe cron string of when this job should run
data?TAdditional data passed in by the scheduler client
namestringThe name of the scheduled job type

ScheduledJob

Ƭ ScheduledJob: Object

Type declaration

NameTypeDescription
dataJSONObject | undefinedAdditional data passed in by the scheduler client
idstringID of the scheduled job. Use this with scheduler.cancelJob to cancel the job.
namestringThe name of the scheduled job type
runAtDateThe Date of when this job should run

ScheduledJobEvent

Ƭ ScheduledJobEvent<T>: Object

Type parameters

NameType
Textends JSONObject | undefined

Type declaration

NameTypeDescription
dataTAdditional data passed in by the scheduler client
namestringThe name of the scheduled job

ScheduledJobHandler

Ƭ ScheduledJobHandler<Data>: (event: ScheduledJobEvent<Data>, context: JobContext) => void | Promise<void>

Type parameters

NameType
Dataextends JSONObject | undefined = JSONObject | undefined

Type declaration

▸ (event, context): void | Promise<void>

Parameters
NameType
eventScheduledJobEvent<Data>
contextJobContext
Returns

void | Promise<void>


ScheduledJobOptions

Ƭ ScheduledJobOptions<T>: Object

Type parameters

NameType
Textends JSONObject | undefined = JSONObject | undefined

Type declaration

NameTypeDescription
data?TAdditional data passed in by the scheduler client
namestringThe name of the scheduled job type
runAtDateThe Date of when this job should run

ScheduledJobType

Ƭ ScheduledJobType<Data>: Object

Type parameters

NameType
Dataextends JSONObject | undefined

Type declaration

NameTypeDescription
namestringThe name of the scheduled job type
onRunScheduledJobHandler<Data>The function that will be called when the job is scheduled to run

Scheduler

Ƭ Scheduler: Object

The Scheduler client lets you schedule new jobs or cancel existing jobs. You must have the scheduler enabled in Devvit.configure to use this client.

Type declaration

NameTypeDescription
cancelJobCancelJobCancel a scheduled job Param The id of the job to cancel
listJobs() => Promise<(ScheduledJob | ScheduledCronJob)[]>Gets the list of all scheduled jobs.
runJob<Data>(job: ScheduledJobOptions<Data> | ScheduledCronJobOptions<Data>) => Promise<string>Schedule a new job to run at a specific time or on a cron schedule

SelectField

Ƭ SelectField: Prettify<BaseField<string[]> & Omit<FieldConfig_Selection, "choices" | "renderAsList" | "minSelections" | "maxSelections"> & { options: FieldConfig_Selection_Item[] ; type: "select" }>

A dropdown field that allows users to pick from a list of options


SetOptions

Ƭ SetOptions: Object

Type declaration

NameTypeDescription
expiration?Date-
nx?booleanOnly set the key if it does not already exist.
xx?booleanOnly set the key if it already exists.

SetStateAction

Ƭ SetStateAction<S>: S | (prevState: S) => S

Type parameters

Name
S

SettingScopeType

Ƭ SettingScopeType: "installation" | "app"


SettingsClient

Ƭ SettingsClient: Object

The Settings API Client lets you retrieve the settings values for your app set by the installer. Use this in conjunction with Devvit.addSettings.

Type declaration

NameType
get<T>(name: string) => Promise<undefined | T>
getAll<T>() => Promise<T>

SettingsFormField

Ƭ SettingsFormField: ValidatedStringField | ValidatedParagraphField | ValidatedNumberField | ValidatedBooleanField | ValidatedSelectField | SettingsFormFieldGroup


SettingsFormFieldGroup

Ƭ SettingsFormFieldGroup: Prettify<Omit<FormFieldGroup, "fields"> & { fields: SettingsFormField[] }>


SettingsFormFieldValidatorEvent

Ƭ SettingsFormFieldValidatorEvent<ValueType>: Object

Type parameters

Name
ValueType

Type declaration

NameType
isEditingboolean
valueValueType | undefined

SettingsValues

Ƭ SettingsValues: Object

Index signature

▪ [key: string]: string | string[] | boolean | number | undefined


StateSetter

Ƭ StateSetter<S>: Dispatch<SetStateAction<S>>

Type parameters

Name
S

StringField

Ƭ StringField: Prettify<BaseField<string> & Omit<FieldConfig_String, "minLength" | "maxLength"> & { isSecret?: boolean ; type: "string" }>

A text field


Toast

Ƭ Toast: Object

Type declaration

NameTypeDescription
appearance?"neutral" | "success"The appearance of the toast
textstringThe message shown within the toast

TriggerContext

Ƭ TriggerContext: Omit<Context, "ui" | "dimensions" | "modLog" | "uiEnvironment">


TriggerDefinition

Ƭ TriggerDefinition: PostSubmitDefinition | PostCreateDefinition | PostUpdateDefinition | PostFlairUpdateDefinition | PostReportDefinition | PostDeleteDefinition | CommentSubmitDefinition | CommentCreateDefinition | CommentUpdateDefinition | CommentReportDefinition | CommentDeleteDefinition | AppInstallDefinition | AppUpgradeDefinition | ModActionDefinition | ModMailDefinition | PostSpoilerUpdateDefinition | PostNsfwUpdateDefinition | OnAutomoderatorFilterPostDefinition | OnAutomoderatorFilterCommentDefinition


TriggerEvent

Ƭ TriggerEvent: PostSubmit | PostCreate | PostUpdate | PostReport | PostDelete | PostFlairUpdate | CommentSubmit | CommentCreate | CommentUpdate | CommentReport | CommentDelete | AppInstall | AppUpgrade | ModActionTrigger | ModMailTrigger | PostNsfwUpdate | PostSpoilerUpdate | AutomoderatorFilterPost | AutomoderatorFilterComment


TriggerEventType

Ƭ TriggerEventType: Object

Maps a TriggerEvent to a Protobuf message and type.

Type declaration

NameType
AppInstall{ type: "AppInstall" } & protos.AppInstall
AppUpgrade{ type: "AppUpgrade" } & protos.AppUpgrade
AutomoderatorFilterComment{ type: "AutomoderatorFilterComment" } & protos.AutomoderatorFilterComment
AutomoderatorFilterPost{ type: "AutomoderatorFilterPost" } & protos.AutomoderatorFilterPost
CommentCreate{ type: "CommentCreate" } & protos.CommentCreate
CommentDelete{ type: "CommentDelete" } & protos.CommentDelete
CommentReport{ type: "CommentReport" } & protos.CommentReport
CommentSubmit{ type: "CommentSubmit" } & protos.CommentSubmit
CommentUpdate{ type: "CommentUpdate" } & protos.CommentUpdate
ModAction{ type: "ModAction" } & protos.ModAction
ModMail{ type: "ModMail" } & protos.ModMail
PostCreate{ type: "PostCreate" } & protos.PostCreate
PostDelete{ type: "PostDelete" } & protos.PostDelete
PostFlairUpdate{ type: "PostFlairUpdate" } & protos.PostFlairUpdate
PostNsfwUpdate{ type: "PostNsfwUpdate" } & protos.PostNsfwUpdate
PostReport{ type: "PostReport" } & protos.PostReport
PostSpoilerUpdate{ type: "PostSpoilerUpdate" } & protos.PostSpoilerUpdate
PostSubmit{ type: "PostSubmit" } & protos.PostSubmit
PostUpdate{ type: "PostUpdate" } & protos.PostUpdate

TriggerOnEventHandler

Ƭ TriggerOnEventHandler<RequestType>: (event: RequestType, context: TriggerContext) => TriggerResult

Type parameters

Name
RequestType

Type declaration

▸ (event, context): TriggerResult

Parameters
NameType
eventRequestType
contextTriggerContext
Returns

TriggerResult


TxClientLike

Ƭ TxClientLike: Object

Type declaration

NameType
del(...keys: string[]) => Promise<TxClientLike>
discard() => Promise<void>
exec() => Promise<any[]>
expire(key: string, seconds: number) => Promise<TxClientLike>
expireTime(key: string) => Promise<TxClientLike>
get(key: string) => Promise<TxClientLike>
getRange(key: string, start: number, end: number) => Promise<TxClientLike>
hDel(key: string, fields: string[]) => Promise<TxClientLike>
hGet(key: string, field: string) => Promise<TxClientLike>
hGetAll(key: string) => Promise<TxClientLike>
hIncrBy(key: string, field: string, value: number) => Promise<TxClientLike>
hKeys(key: string) => Promise<TxClientLike>
hLen(key: string) => Promise<TxClientLike>
hMGet(key: string, fields: string[]) => Promise<TxClientLike>
hScan(key: string, cursor: number, pattern?: string, count?: number) => Promise<TxClientLike>
hSet(key: string, fieldValues: { [field: string]: string; }) => Promise<TxClientLike>
hdel(key: string, fields: string[]) => Promise<TxClientLike>
hget(key: string, field: string) => Promise<TxClientLike>
hgetall(key: string) => Promise<TxClientLike>
hincrby(key: string, field: string, value: number) => Promise<TxClientLike>
hkeys(key: string) => Promise<TxClientLike>
hlen(key: string) => Promise<TxClientLike>
hscan(key: string, cursor: number, pattern?: string, count?: number) => Promise<TxClientLike>
hset(key: string, fieldValues: { [field: string]: string; }) => Promise<TxClientLike>
incrBy(key: string, value: number) => Promise<TxClientLike>
mGet(keys: string[]) => Promise<TxClientLike>
mSet(keyValues: { [key: string]: string; }) => Promise<TxClientLike>
mget(keys: string[]) => Promise<TxClientLike>
mset(keyValues: { [key: string]: string; }) => Promise<TxClientLike>
multi() => Promise<void>
set(key: string, value: string, options?: SetOptions) => Promise<TxClientLike>
setRange(key: string, offset: number, value: string) => Promise<TxClientLike>
strLen(key: string) => Promise<TxClientLike>
strlen(key: string) => Promise<TxClientLike>
type(key: string) => Promise<TxClientLike>
unwatch() => Promise<TxClientLike>
watch(...keys: string[]) => Promise<TxClientLike>
zAdd(key: string, ...members: ZMember[]) => Promise<TxClientLike>
zCard(key: string) => Promise<TxClientLike>
zIncrBy(key: string, member: string, value: number) => Promise<TxClientLike>
zRange(key: string, start: string | number, stop: string | number, options?: ZRangeOptions) => Promise<TxClientLike>
zRank(key: string, member: string) => Promise<TxClientLike>
zRem(key: string, members: string[]) => Promise<TxClientLike>
zRemRangeByLex(key: string, min: string, max: string) => Promise<TxClientLike>
zRemRangeByRank(key: string, start: number, stop: number) => Promise<TxClientLike>
zRemRangeByScore(key: string, min: number, max: number) => Promise<TxClientLike>
zScan(key: string, cursor: number, pattern?: string, count?: number) => Promise<TxClientLike>
zScore(key: string, member: string) => Promise<TxClientLike>

UIClient

Ƭ UIClient: Object

The UI client lets your app interact with the Reddit frontend. This client will only be available for capabilities that have a frontend component, such as within the Custom Post component's event handlers, a Form's onSubmit handler, and Menu items.

Type declaration

NameTypeDescription
webViewWebViewUIClientInteract with WebView blocks
navigateTo(url: string) => void(subreddit: Subreddit) => void(post: Post) => void(comment: Comment) => void(user: User) => void(urlOrThing: string | User | Subreddit | Post | Comment) => voidNavigate to a URL
showForm(formKey: FormKey, data?: JSONObject) => voidOpen a form in a modal
showToast(text: string) => void(toast: Toast) => voidShow a message in a toast.

UploadMediaOptions

Ƭ UploadMediaOptions: Object

Type declaration

NameType
type"image" | "gif" | "video"
urlstring

UseAsyncResult

Ƭ UseAsyncResult<S>: Object

Type parameters

Name
S

Type declaration

NameType
dataS | null
errorAsyncError | null
loadingboolean

UseChannelHook

Ƭ UseChannelHook<Message>: (options: ChannelOptions<Message>) => UseChannelResult<Message>

Type parameters

NameType
Messageextends JSONValue = JSONValue

Type declaration

▸ (options): UseChannelResult<Message>

Parameters
NameType
optionsChannelOptions<Message>
Returns

UseChannelResult<Message>


UseChannelResult

Ƭ UseChannelResult<Message>: Object

Type parameters

NameType
Messageextends JSONValue = JSONValue

Type declaration

NameTypeDescription
statusChannelStatusCurrent subscription status
send(msg: Message) => Promise<void>Publish a message to the channel
subscribe() => voidSubscribe to the channel
unsubscribe() => voidUnsubscribe from the channel

UseFormHook

Ƭ UseFormHook<T>: (form: T, onSubmit: (values: FormToFormValues<T>) => void | Promise<void>) => FormKey

A hook that returns a form key that can be used in the ui.showForm

Type parameters

NameType
Textends Form | FormFunction = Form | FormFunction

Type declaration

▸ (form, onSubmit): FormKey

Parameters
NameType
formT
onSubmit(values: FormToFormValues<T>) => void | Promise<void>
Returns

FormKey


UseIntervalHook

Ƭ UseIntervalHook: (callback: () => void | Promise<void>, delay: number) => UseIntervalResult

A hook that can used to run a callback on an interval between Block renders. Only one useInterval hook may be running at a time.

Type declaration

▸ (callback, delay): UseIntervalResult

Parameters
NameType
callback() => void | Promise<void>
delaynumber
Returns

UseIntervalResult


UseIntervalResult

Ƭ UseIntervalResult: Object

An object that contains functions to start and stop the interval created by the useInterval hook

Type declaration

NameTypeDescription
start() => voidStart the interval
stop() => voidStop the interval

UseStateHook

Ƭ UseStateHook: Context["useState"]


UseStateInitializer

Ƭ UseStateInitializer<S>: S | () => S | AsyncUseStateInitializer<S>

Type parameters

Name
S

UseStateResult

Ƭ UseStateResult<S>: [S, StateSetter<S>]

A tuple containing the current state and a function to update it

Type parameters

Name
S

ValidatedBooleanField

Ƭ ValidatedBooleanField: Prettify<ValidatedFormField<BooleanField, boolean>>


ValidatedFormField

Ƭ ValidatedFormField<Field, ValueType>: Omit<Field, "required"> & { onValidate?: OnValidateHandler<ValueType> }

Type parameters

Name
Field
ValueType

ValidatedNumberField

Ƭ ValidatedNumberField: Prettify<ValidatedFormField<NumberField, number>>


ValidatedParagraphField

Ƭ ValidatedParagraphField: Prettify<ValidatedFormField<ParagraphField, string>>


ValidatedSelectField

Ƭ ValidatedSelectField: Prettify<ValidatedFormField<SelectField, string[]>>


ValidatedStringField

Ƭ ValidatedStringField: Prettify<ValidatedFormField<StringField, string>>


ZMember

Ƭ ZMember: Object

Type declaration

NameType
memberstring
scorenumber

ZRangeByScoreOptions

Ƭ ZRangeByScoreOptions: Object

Type declaration

NameType
limit?{ count: number ; offset: number }
limit.countnumber
limit.offsetnumber
withScores?boolean

ZRangeOptions

Ƭ ZRangeOptions: Object

Type declaration

NameTypeDescription
by"score" | "lex" | "rank"-
reverse?booleanReverses the sorted set, with index 0 as the element with the highest score.

Variables

ALL_ICON_NAMES

Const ALL_ICON_NAMES: readonly ["3rd-party", "activity", "add-emoji", "add", "add-media", "add-to-feed", "admin", "ads", "ai", "align-center", "align-left", "align-right", "all", "ama", "appearance", "approve", "archived", "aspect-ratio", "aspect-rectangle", "attach", "audience", "audio", "author", "automod", "avatar-style", "award", "back", "backup", "ban", "best", "block", "blockchain", "bold", "boost", "bot", "bounce", "brand-awareness", "browse", "browser", "cake", "calendar", "camera", "campaign", "caret-down", "caret-left", "caret-right", "caret-up", "chat", "chat-group", "chat-new", "chat-private", "checkbox-dismiss", "checkbox", "checkmark", "chrome", "clear", "client-list", "close", "closed-captioning", "code-block", "code-inline", "coins-color-old", "coins", "collapse-left", "collapse-right", "collectible-expressions", "collection", "comment", "comments", "communities", "community", "confidence", "contest", "controversial", "conversion", "copy-clipboard", "crop", "crosspost", "crowd-control", "custom-feed", "customize", "dashboard", "day", "delete-column", "delete", "delete-row", "devvit", "discover", "dismiss-all", "distinguish", "down-arrow", "down", "download", "downvote", "downvotes", "drag", "drugs", "duplicate", "edit", "effect", "embed", "emoji", "end-live-chat", "error", "expand-left", "expand-right", "external", "feed-video", "filter", "format", "forward", "funnel", "gif-post", "gold", "hashtag", "heart", "help", "hide", "history", "home", "hot", "ignore-reports", "image-post", "inbox", "info", "insert-column-left", "insert-column-right", "insert-row-above", "insert-row-below", "internet", "invite", "italic", "join", "joined", "jump-down", "jump-up", "karma", "keyboard", "kick", "language", "leave", "left", "link", "link-post", "list-bulleted", "list-numbered", "live-chat", "live", "load", "location", "lock", "logout", "loop", "macro", "mark-read", "marketplace", "mask", "media-gallery", "meme", "menu", "message", "mic", "mic-mute", "mod", "mod-mail", "mod-mode", "mod-mute", "mod-overflow", "mod-queue", "mod-unmute", "music", "mute", "new", "night", "no-internet", "notification", "notification-frequent", "notification-off", "nsfw", "nsfw-language", "nsfw-violence", "official", "original", "overflow-caret", "overflow-horizontal", "overflow-vertical", "pause", "payment", "peace", "pending-posts", "phone", "pin", "play", "poll-post", "popular", "posts", "powerup", "predictions", "premium", "privacy", "profile", "qa", "qr-code", "quarantined", "quote", "r-slash", "radar", "radio-button", "raise-hand", "random", "ratings-everyone", "ratings-mature", "ratings-nsfw", "ratings-violence", "recovery-phrase", "refresh", "removal-reasons", "remove", "reply", "report", "reverse", "rich-text", "right", "rising", "rotate", "rotate-image", "rpan", "rules", "safari", "save", "save-view", "saved", "saved-response", "search", "self", "send", "settings", "severity", "share", "share-new", "show", "side-menu", "skipback10", "skipforward10", "sort-az", "sort", "sort-price", "sort-za", "spam", "spoiler", "sponsored", "spreadsheet", "star", "statistics", "status-live", "sticker", "strikethrough", "subtract", "superscript", "swap-camera", "swipe-back", "swipe-down", "swipe", "swipe-up", "table", "tag", "tap", "text", "text-post", "text-size", "toggle", "tools", "top", "topic-activism", "topic-addictionsupport", "topic-advice", "topic-animals", "topic-anime", "topic-art", "topic-beauty", "topic-business", "topic-careers", "topic-cars", "topic-celebrity", "topic-craftsdiy", "topic-crypto", "topic-culture", "topic-diy", "topic-entertainment", "topic-ethics", "topic-family", "topic-fashion", "topic", "topic-fitness", "topic-food", "topic-funny", "topic-gender", "topic-health", "topic-help", "topic-history", "topic-hobbies", "topic-homegarden", "topic-internet", "topic-law", "topic-learning", "topic-lifestyle", "topic-marketplace", "topic-mature", "topic-mensfashion", "topic-menshealth", "topic-meta", "topic-military", "topic-movies", "topic-music", "topic-news", "topic-other", "topic-outdoors", "topic-pets", "topic-photography", "topic-places", "topic-podcasts", "topic-politics", "topic-programming", "topic-reading", "topic-religion", "topic-science", "topic-sexorientation", "topic-sports", "topic-style", "topic-tabletop", "topic-technology", "topic-television", "topic-traumasupport", "topic-travel", "topic-videogaming", "topic-womensfashion", "topic-womenshealth", "translate", "translation-off", "trim", "u-slash", "unban", "undo", "unheart", "unlock", "unmod", "unpin", "unstar", "unverified", "up-arrow", "up", "upload", "upvote", "upvotes", "user", "user-note", "users", "vault", "verified", "video-camera", "video-feed", "video-post", "video-thread", "video-transcription", "view-card", "view-classic", "view-compact", "view-grid", "view-sort", "views", "volume", "wallet", "warning", "webhook", "whale", "wiki-ban", "wiki", "wiki-unban", "world", "coins-color", "powerup-color", "powerup-fill-color", "share-android", "share-ios", "video-live-1", "video-live-fill-1", "video-live", "volume-mute", "binoculars", "caret-updown", "planet", "telescope"]

Functions

svg

svg(strings, ...args): `data:image/svg+xml;charset=UTF-8,${string}` | ""

A helper to allow SVG functionality within image tags.

Parameters

NameType
stringsTemplateStringsArray
...args(string | number)[]

Returns

`data:image/svg+xml;charset=UTF-8,${string}` | ""

Example

import { Devvit, svg } from '@devvit/public-api';
const App = () => {
const color = 'gold'
return (
<hstack>
<image
url={svg`<svg viewBox="0 0 10 10" xmlns="http://www.w3.org/2000/svg">
<circle fill="${color}" cx="5" cy="5" r="4" />
</svg>`}
imageHeight={100}
imageWidth={100}
/>
</hstack>
)
}

useAsync

useAsync<S>(initializer, options?): UseAsyncResult<S>

This is the preferred way to handle async state in Devvit.

Type parameters

NameType
Sextends JSONValue

Parameters

NameTypeDescription
initializerAsyncUseStateInitializer<S>any async function that returns a JSONValue
optionsAsyncOptions<S>-

Returns

UseAsyncResult<S>

UseAsyncResult


useChannel

useChannel<Message>(opts): UseChannelResult<Message>

Type parameters

NameType
Messageextends JSONValue

Parameters

NameType
optsReadonly<ChannelOptions<Message>>

Returns

UseChannelResult<Message>


useForm

useForm<T>(form, onSubmit): FormKey

Type parameters

NameType
Textends Form | FormFunction

Parameters

NameType
formT
onSubmit(values: FormToFormValues<T>) => void | Promise<void>

Returns

FormKey


useInterval

useInterval(callback, requestedDelayMs): UseIntervalResult

Parameters

NameType
callback() => void | Promise<void>
requestedDelayMsnumber

Returns

UseIntervalResult


useState

useState(initialState): UseStateResult<boolean>

Parameters

NameType
initialStateUseStateInitializer<boolean>

Returns

UseStateResult<boolean>

useState(initialState): UseStateResult<number>

Parameters

NameType
initialStateUseStateInitializer<number>

Returns

UseStateResult<number>

useState(initialState): UseStateResult<string>

Parameters

NameType
initialStateUseStateInitializer<string>

Returns

UseStateResult<string>

useState<S>(initialState): UseStateResult<S>

Type parameters

NameType
Sextends JSONValue

Parameters

NameType
initialStateUseStateInitializer<S>

Returns

UseStateResult<S>

  • Table of contents
  • Type Aliases
    • AllIconName
    • AppInstall
    • AppInstallDefinition
    • AppUpgrade
    • AppUpgradeDefinition
    • AsyncError
    • AsyncUseStateInitializer
    • AutomoderatorFilterComment
    • AutomoderatorFilterPost
    • BaseContext
    • BaseField
    • BlockElement
    • BooleanField
    • CancelJob
    • CommentCreate
    • CommentCreateDefinition
    • CommentDelete
    • CommentDeleteDefinition
    • CommentReport
    • CommentReportDefinition
    • CommentSubmit
    • CommentSubmitDefinition
    • CommentUpdate
    • CommentUpdateDefinition
    • Configuration
    • Context
    • ContextAPIClients
    • ContextDebugInfo
    • CustomPostType
    • Data
    • DevvitDebug
    • Dispatch
    • Form
    • FormDefinition
    • FormField
    • FormFieldGroup
    • FormFunction
    • FormKey
    • FormOnSubmitEvent
    • FormOnSubmitEventHandler
    • FormToFormValues
    • FormValues
    • IconName
    • ImageField
    • JSONArray
    • JSONObject
    • JSONPrimitive
    • JSONValue
    • JobContext
    • KVStore
    • MediaAsset
    • MediaPlugin
    • MenuItem
    • MenuItemLocation
    • MenuItemOnPressEvent
    • MenuItemPostFilter
    • MenuItemUserType
    • ModActionDefinition
    • ModActionTrigger
    • ModMailDefinition
    • ModMailTrigger
    • MultiTriggerDefinition
    • NumberField
    • OnAutomoderatorFilterCommentDefinition
    • OnAutomoderatorFilterPostDefinition
    • OnTriggerRequest
    • OnValidateHandler
    • ParagraphField
    • PartialJSONArray
    • PartialJSONObject
    • PartialJSONPrimitive
    • PartialJSONValue
    • PluginSettings
    • PostCreate
    • PostCreateDefinition
    • PostDelete
    • PostDeleteDefinition
    • PostFlairUpdate
    • PostFlairUpdateDefinition
    • PostNsfwUpdate
    • PostNsfwUpdateDefinition
    • PostReport
    • PostReportDefinition
    • PostSpoilerUpdate
    • PostSpoilerUpdateDefinition
    • PostSubmit
    • PostSubmitDefinition
    • PostUpdate
    • PostUpdateDefinition
    • RedisClient
    • RunJob
    • ScheduledCronJob
    • ScheduledCronJobOptions
    • ScheduledJob
    • ScheduledJobEvent
    • ScheduledJobHandler
    • ScheduledJobOptions
    • ScheduledJobType
    • Scheduler
    • SelectField
    • SetOptions
    • SetStateAction
    • SettingScopeType
    • SettingsClient
    • SettingsFormField
    • SettingsFormFieldGroup
    • SettingsFormFieldValidatorEvent
    • SettingsValues
    • StateSetter
    • StringField
    • Toast
    • TriggerContext
    • TriggerDefinition
    • TriggerEvent
    • TriggerEventType
    • TriggerOnEventHandler
    • TxClientLike
    • UIClient
    • UploadMediaOptions
    • UseAsyncResult
    • UseChannelHook
    • UseChannelResult
    • UseFormHook
    • UseIntervalHook
    • UseIntervalResult
    • UseStateHook
    • UseStateInitializer
    • UseStateResult
    • ValidatedBooleanField
    • ValidatedFormField
    • ValidatedNumberField
    • ValidatedParagraphField
    • ValidatedSelectField
    • ValidatedStringField
    • ZMember
    • ZRangeByScoreOptions
    • ZRangeOptions
  • Variables
    • ALL_ICON_NAMES
  • Functions
    • svg
    • useAsync
    • useChannel
    • useForm
    • useInterval
    • useState