Skip to content

Commit 2747050

Browse files
committed
useAgent
1 parent 34667bc commit 2747050

File tree

1 file changed

+26
-4
lines changed

1 file changed

+26
-4
lines changed

src/content/docs/agents/examples/manage-and-sync-state.mdx

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -92,18 +92,40 @@ export class MyAgent extends Agent<Env, FlightRecord> {
9292

9393
### Synchronizing state
9494

95-
Clients can connect to an Agent and stay synchronized with its state using the React hooks provided as part of `@cloudflare/agents/react`:
95+
Clients can connect to an Agent and stay synchronized with its state using the React hooks provided as part of `@cloudflare/agents/react`.
96+
97+
A React application can call `useAgent` to connect to a named Agent over WebSockets at
9698

9799
<TypeScriptExample>
98100

99101
```ts
100-
101-
102+
import { useState } from "react";
103+
import { useAgent } from "@cloudflare/agents/react";
104+
105+
function StateInterface() {
106+
const [state, setState] = useState({ counter: 0 });
107+
108+
const agent = useAgent({
109+
agent: "thinking-agent",
110+
name: "my-agent",
111+
onStateUpdate: (newState) => setState(newState),
112+
});
113+
114+
const increment = () => {
115+
agent.setState({ counter: state.counter + 1 });
116+
};
117+
118+
return (
119+
<div>
120+
<div>Count: {state.counter}</div>
121+
<button onClick={increment}>Increment</button>
122+
</div>
123+
);
124+
}
102125
```
103126

104127
</TypeScriptExample>
105128

106-
107129
The state synchronization system:
108130

109131
* Automatically syncs the Agent's state to all connected clients

0 commit comments

Comments
 (0)