Send Event to React Component After Creating

This question is similar to this one.

I’ve created a custom component (3d model viewer) that uses useReducer to manage its state. I’d like to send events to the component that would be interpreted as a reducer action. Through this method I’d be able to create a python api for manipulating the view after creating the component and loading the data.

# pseudo code / not a python pro
def st_viewer_clear(st_viewer):
    st_viewer.dispatch( { "type": "remove-all" } )

It seems possible to trigger an event in the component the same way Streamlit sends events that are handled by Streamlit.onMessageEvent().

I can register an event listener from within my component but I can’t figure out how to emit a new event from python. Is this possible?

Thanks in advance :pray:

The Python page needs to rerun, loading the component afresh which will send over any new initializer prop values. You should pass these prop values as session state K-V pairs so they survive the rerun.

[HACK] Otherwise, have your component periodically poll an external service that serves as a command dispatch queue. Your Streamlit app can push commands into this queue, which the component will pick up and execute. I’ve used Airtable and FastAPI microservices for this purpose.

It’s not ideal and I’m open to other suggestions.

Arvindra

Thanks - I’ve been working with the session_state approach with limited success.

I don’t think I want to try setting up a backend service for an app that I would hope to deploy and share at some point.

Yes it adds quite a lot of friction for something that should be easy. You could launch a FastAPI server thread from your Streamlit app like I do here: https://github.com/asehmi/simple-streamlit-fastapi-integration

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.