Skip to content

Commit 61c545b

Browse files
committed
initial state
1 parent 431bcdc commit 61c545b

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

src/content/docs/agents/api-reference/store-and-sync-state.mdx

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,36 @@ export class MyAgent extends Agent<Env, FlightRecord> {
9393

9494
</TypeScriptExample>
9595

96+
### Set the initial state for an Agent
97+
98+
You can also set the initial state for an Agent via the `initialState` property on the `Agent` class:
99+
100+
<TypeScriptExample>
101+
102+
```ts
103+
type State = {
104+
counter: number;
105+
text: string;
106+
color: string;
107+
};
108+
109+
class MyAgent extends Agent<Env, State> {
110+
// Set a default, initial state
111+
initialState = {
112+
counter: 0,
113+
text: "",
114+
color: "#3B82F6",
115+
};
116+
117+
doSomething() {
118+
console.log(this.state); // {counter: 0, text: "", color: "#3B82F6"}, if you haven't set the state yet
119+
}
120+
}
121+
```
122+
</TypeScriptExample>
123+
124+
Any initial state is synced to clients connecting via [the `useAgent` hook](#synchronizing-state).
125+
96126
### Synchronizing state
97127

98128
Clients can connect to an Agent and stay synchronized with its state using the React hooks provided as part of `agents-sdk/react`.

0 commit comments

Comments
 (0)