thunderbug1 / streamlit-javascript

Streamlit component to execute javascript code on the client side and get back the result
MIT License
102 stars 3 forks source link

Does returning things back to streamlit require an async function? #10

Open nihirisuto opened 1 year ago

nihirisuto commented 1 year ago

Heyo first just want to say this is a mega clutch addition to streamlit thank you for putting this together.

I was able to use this addon to get the end result I wanted (pass a JSON to a javascript function to restructure the JSON and return to streamlit), but I only seem to be able to get this to work if I leave everything inside the example await fetch() async function (the .then() method seems to run every line of code I throw inside it). Final step of my function does do a return, but I can't do this outside of a function and for some reason when I tried to just.. write a javascript function followed by calling that function, I wasn't getting anything back.

Here's an absolutely abysmal example:

# Does not work 
def test(jsonstring):
   return st_javascript(f'''
        function fixjson(jsonstring) {{
            var obj = JSON.Parse(jsonstring);
            /* do a bunch of stuff to json */
            return obj;
        }};

        fixjson('{jsonstring}');
    ''')

st.write(test('{"test":"weeee"}'))

# Works 
def test(jsonstring):
   return st_javascript(f'''await fetch("https://reqres.in/api/products/3").then(function(response) {{
            var obj = JSON.Parse('{jsonstring}');
            /* do a bunch of stuff to json */
            return obj;
        }});
    ''')

st.write(test('{"test":"weeee"}'))

I can understand how this would work if I was to just paste the whole thing into the javascript console in a web browser, but wondering if there's a better way to do this. Not the best at JS. Right now I'm... actually hitting the api for your example every time I try to run my streamlit app. That seems a little silly, and I'm sure there's a better way.

Cheers

Socvest commented 1 year ago

Have a look at this. Solved my problem for me.