State management for container widgets using React #362
Unanswered
kylebarron
asked this question in
General
Replies: 1 comment
-
I ended up solving this in developmentseed/lonboard#34. In particular, only the top-level model uses anywidget's |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Making this discussion topic to see if anyone has some ideas/best practices. In my anywidget-based widget, I currently have each map layer as its own self-contained widget subclassing from
anywidget.AnyWidget
. It would be nice if you could render multiple data layers on the same map. This in effect becomes a container widget, where theMap
widget is just a container for multiple data layers that are themselves widgets (though maybe not DOMWidgets). See container discussion #293 and #194.It's important in general with widgets to have accurate event notifications. If an attribute changes in Python, you want your JS side to be updated with that new attribute value. The core question is: how to manage state and event notifications on the sub widgets with React?
If we have a Python widget like:
then on the JS side we can use
useModelState
from@anywidget/react
on the top-levelMap
widget, but when we do that on the"layers"
key, we get an array of strings, each of which represents a sub-model. But then we need to call the asyncmodel.widget_manager.get_model
to actually access the sub-model:The issue here is that
childLayerIds
does not change when a sub-model is mutated. That array of strings is constant unless you add another layer. So thatuseEffect
pretty much only runs once.You can't have a different number of hooks across render passes, so you can't do something like a local
useLocalModelState
on the sub models, because you'll have an unknown number of sub-models that could change.Presumably I need some custom state solution. Maybe for now I should get by with just a single state object, where the first level is keyed by the model ID and the second level is keyed by all the state. But I'm wondering if people with more JS knowledge have some tips to share here.
Beta Was this translation helpful? Give feedback.
All reactions