-
-
Notifications
You must be signed in to change notification settings - Fork 328
-
Description:
How can I set state in child function? With my code it triggers infinite loop.
@component def parent(): a, set_a = use_state("") return child(set_a) @component def child(set_a): set_a("test") print("function call") return html.p("test") run(parent)
Beta Was this translation helpful? Give feedback.
All reactions
Replies: 3 comments 4 replies
-
@rmorshea I just asked @jkrobicki to check because I am not sure if this is intended behavior, if it is I could write some docs to explain why it happens.
Beta Was this translation helpful? Give feedback.
All reactions
-
This might be a bug. I would've expected the code below to resolve the infinite looping... but ironically it doesn't.
@component def parent(): a, set_a = idom.hooks.use_state("") return child(a, set_a) @component def child(a, set_a): if a != "test": set_a("test") print("function call") return html.p("test") run(parent)
Beta Was this translation helpful? Give feedback.
All reactions
-
but is this a behavior we want? Should child() be able to change the state of a value it depends from?
Beta Was this translation helpful? Give feedback.
All reactions
-
This one definitely seems like a bug. The other is not.
Beta Was this translation helpful? Give feedback.
All reactions
-
I think this fixes it: #688
Beta Was this translation helpful? Give feedback.
All reactions
-
The originally posted code snippet is intended behavior. It happens because:
- We change the state value as soon as we render.
- The value we set the state to is always different - IDOM performs identity checks to see if things changed (i.e.
"test" is not "test")
I've never seen any reason why someone would want to set a value as they are rendering. This is because, as soon as one view renders, the next one will begin. Typically this leads to the view flashing from one thing to the next so fast that it's unreadable.
If you need to set something after rendering (usually to load some resource from a database that may take some time to respond), you'd do that in an "effect".
Beta Was this translation helpful? Give feedback.
All reactions
-
With that said, I've only just realized that in javascript "test" === "test" is true while "{} === {}" is false. I would have expected the string comparison to also be false if it were doing any sort of true "identity check". So maybe IDOM should make a special exception for strings/ints when comparing.
Beta Was this translation helpful? Give feedback.