#Wait for clean state to finish

1 messages · Page 1 of 1 (latest)

surreal whale
#

Hi all!

Im doing the following to clean the (previous) state, before triggering a new run:


    setState((prev) => ({ ...prev!, generated_report: "" }))
    await new Promise((resolve) => setTimeout(resolve, 100))
    run(() => new TextMessage({
          role: MessageRole.User,
          content: 'Generate the report!',
    }))

If i take out the 100ms wait, then the run() method runs concurrently as the cleaning setState, and flickering ocurrs.
How does one elegantly wait for the state to be cleaned up, in this case, the generated_report state variable, before calling run()?

loud mirage
#

Hello @surreal whale ,
Since React state updates are asynchronous, there's no built‐in way to "await" a state change.
Instead of using an arbitrary delay (like setTimeout), another approach is to trigger your run() call in a useEffect hook that watches for the change in your generated_report state.
For example:

• Update your state: setState(prev => ({ ...prev, generated_report: "" }));

• Then use an effect: useEffect(() => { if (state.generated_report === "") { run(() => new TextMessage({ role: MessageRole.User, content: 'Generate the report!', })); } }, [state.generated_report]);

This way, once React has flushed the state update and re-rendered the component, the effect runs and triggers your run() call without needing an arbitrary timeout.