reflex-dev / reflex

🕸️ Web apps in pure Python 🐍
https://reflex.dev
Apache License 2.0
18.87k stars 1.07k forks source link

Python event chains corrupts JSON string data #1429

Open allComputableThings opened 1 year ago

allComputableThings commented 1 year ago

See: https://discord.com/channels/1029853095527727165/1133885037872435340

I'd like to pass a MyElement object between event handlers.

The constructor data is provided as:

{
 'id': '9',
 'content': '{"action":"foo",\n'
            ' "type":"bar",\n'
            '}',
}

State2.saveItem(MyElement(**item)) fails -- MyElement is not JSON serializable is raised.

So, I pass it as a dict: State2.saveItem(item).

The string: '{"id": "9", "content": "action":"foo",\n "type":"bar",\n}' is received. This is not JSON of the the original object and is in fact invalid json (curly brace missing before "action").

import pprint
import typing
import reflex as rx
import json
class MyElement_(rx.Base):
    id: typing.Optional[str]
    content: str

item = {
 'id': '9',
 'content': '{"action":"foo",\n'
            ' "type":"bar",\n'
            '}',
}

class State2(rx.State):

  async def click(self):
      print(f"click:")
      #return [State2.saveItem(MyElement_(**item))]  # Fails, with MyElement_ not json serializable
      return [State2.saveItem(item)]

  async def saveItem(self, item:MyElement_):
      print(f"saveItem:", type(item))  #str received (dict sent)
      pprint.pprint(item)     # Yuk! What have I been given!
      obj = json.loads(item)  # Fail
      print("obj", type(obj))
      pprint.pprint(obj)
      ce = MyElement_(**obj)

def index():
    return rx.button("Clickme", on_click=State2.click)

app = rx.App(state=State2)
app.add_page(index)
app.compile()

Braces, not new lines seem to be the cause: Also fails with:

item = {
 'id': '9',
 'content': '{123',
}
kylelee1027 commented 4 months ago

Hello, I'm trying to find bugs and fix bugs in an open source repo for a class assignment. Any tips on how to get started tackling this issue on would be greatly appreciated!