|
| 1 | +--- |
| 2 | +title: "Guide: Frames.js State" |
| 3 | +description: "Frames.js is the react based framework for making frames. Debugger included." |
| 4 | +--- |
| 5 | + |
| 6 | +# Guide: State Management in Frames.js |
| 7 | + |
| 8 | +State in Frames.js is a way for you to store data that you want to use in between frames requests. The frames spec allows up to 4kb of data to be stored in the state object. |
| 9 | + |
| 10 | +## Setup |
| 11 | + |
| 12 | +To use state in frames.js, you should declare the initial state in your `createFrames` call. If your state type is not declared explicitly it will be derived from the initial state. |
| 13 | + |
| 14 | +```ts [frames.ts] |
| 15 | +import { createFrames } from "@framesjs/next"; |
| 16 | + |
| 17 | +export type State = { |
| 18 | + count: number; |
| 19 | +}; |
| 20 | + |
| 21 | +export const frames = createFrames<State>({ |
| 22 | + initialState: { |
| 23 | + count: 0, |
| 24 | + }, |
| 25 | +}); |
| 26 | +``` |
| 27 | + |
| 28 | +## Accessing state |
| 29 | + |
| 30 | +You can access the state object in your frame on the `ctx` parameter. The initial frame will have the state object with the initial values. |
| 31 | + |
| 32 | +```ts [route.tsx] |
| 33 | +import { frames } from "./frames"; |
| 34 | + |
| 35 | +const handler = frames(async ({ ctx }) => { |
| 36 | + return { |
| 37 | + image: <div tw="flex">Count: {ctx.state.count}</div>, // [!code focus] |
| 38 | + }; |
| 39 | +}); |
| 40 | + |
| 41 | +export const GET = handler; |
| 42 | +export const POST = handler; |
| 43 | +``` |
| 44 | + |
| 45 | +## Updating state |
| 46 | + |
| 47 | +To update the state, you just include the updated state object in your handler's [`FrameDefinition`](/reference/core/createFrames#framedefinition) return value. |
| 48 | + |
| 49 | +```ts [route.tsx] |
| 50 | +import { frames, Button } from "./frames"; |
| 51 | + |
| 52 | +const handler = frames(async ({ ctx }) => { |
| 53 | + const currentState = ctx.state; |
| 54 | + |
| 55 | + // Update the state // [!code focus] |
| 56 | + const updatedState = { // [!code focus] |
| 57 | + ...currentState, // [!code focus] |
| 58 | + count: currentState.count + 1, // [!code focus] |
| 59 | + }; // [!code focus] |
| 60 | + |
| 61 | + return { |
| 62 | + image: <div tw="flex">Count: {updatedState.count}`</div>, // [!code focus], |
| 63 | + buttons: [ |
| 64 | + <Button action="post">Increment</Button> |
| 65 | + ], |
| 66 | + state: updatedState, // [!code focus] |
| 67 | + }; |
| 68 | +}); |
| 69 | +
|
| 70 | +export const GET = handler; |
| 71 | +export const POST = handler; |
| 72 | +``` |
0 commit comments