Use case
When I create a component,
I would like to load data from an API using the pyscript.fetch function, which is async.
What I tried
This can not be done during populate() because the function is synchron.
triggering an event, which could be used to trigger the data loading does also not work, because at the time of populate() the element is not part of the DOM.
I found the undocumented on_ready callback on the component, but it is also synchron, so fetching data is also no option here.
My solution so far
I use the on_ready method to trigger an effect event, which triggers an async on_effect method, which can load data async ✨
class CustomPage(Page):
def __init__(self, *args, **kwargs):
super().__init__(*args, on_effect=self._on_effect, **kwargs)
def on_ready(self):
self.trigger_event("effect")
async def _on_effect(self, _):
# pass the event to the on_effect method, without the obsolete event argument
await self.on_effect()
async def on_effect(self):
"""Called after the page is ready."""
pass
@app.page()
class DefaultPage(CustomPage):
def initial(self):
return {"items": [], "loading": True}
async def on_effect(self):
await fetch(....)
PS would be great to add on_ready to the docs.
Use case
When I create a component,
I would like to load data from an API using the
pyscript.fetchfunction, which is async.What I tried
This can not be done during
populate()because the function is synchron.triggering an event, which could be used to trigger the data loading does also not work, because at the time of
populate()the element is not part of the DOM.I found the undocumented on_ready callback on the component, but it is also synchron, so fetching data is also no option here.
My solution so far
I use the
on_readymethod to trigger aneffectevent, which triggers an asyncon_effectmethod, which can load data async ✨