agents icon indicating copy to clipboard operation
agents copied to clipboard

Feature Request: updateState hook

Open kchro3 opened this issue 9 months ago • 4 comments

Also open to other ideas, since I'm not that proficient in React.

I'm running into situations where I want to update the Agent state from the frontend, so what I've been doing is something like the following:

export interface ManagerState {
  fieldA: string
  fieldB: string
}

// agent backend
export default class Manager extends Agent<Env, ManagerState> {
  ...
}

// agent frontend
function Component() {
  const [fieldA, setFieldA] = useState<string>("");
  const [state, setState] = useState<ManagerState | null>(null);
  const agent = useAgent<ManagerState>({
    agent: "manager",
    ...
    onStateUpdate: setState,
  });

  useEffect(() => {
    if (agent && state) {
      agent.setState({ ...state, fieldA });
    }
  }, [agent, fieldA);

  return ...
}

in this example, i have a shared state with multiple fields, and i want to update part of the state in a useEffect hook. you can imagine that maybe there's an input field where i want to update the fieldA locally & synchronize it with the agent state.

the agent & state null checks on the frontend are necessary because it will nullify the agent state on page load.

the state should technically be a dependency, but it would cause an infinite render loop.

is it possible to expose an updateState hook that would update the state similar to useImmer? not sure if that would resolve the issue since i'm not sure how agent.setState works under the hood.

kchro3 avatar Apr 11 '25 00:04 kchro3

I don't recommend using a useEffect to synchronise state though, just call agent.setState directly. That calls onStateUpdate synchronously.

also: agent will never be null, so you don't have to do a null check on it We could suspend until initial state comes in, so you don't have to do a null check there

threepointone avatar Apr 11 '25 08:04 threepointone

Either way, would having an update state be useful? I think the "problem" is that I need to maintain a local state in order to update the agent state.

kchro3 avatar Apr 11 '25 21:04 kchro3

Is that a problem tho? We specifically designed it so you can use your own state variable.

threepointone avatar Apr 15 '25 09:04 threepointone

This is a different point than the initial issue, but couldn't there be race conditions if the local state isn't up to date?

For example, let's say you have a multi chat app, and everyone is connected to the same agent. If everyone is trying to update the state at the same time, would you need to have locks? Even if the DO is single-threaded, that doesn't guarantee that the local state is up to date, right?

kchro3 avatar Apr 15 '25 17:04 kchro3