How can I set some state every time data
changes?
#4217
-
How can I conditionally set some state, based on
For example, in this example I've prepared, if a client has a single car, then I'd like to preselect it the moment I select that client. cc @TkDodo |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
I have also been struggling with this design pattern. My current solution that I am working towards is using This is proving to be pretty difficult because there doesn't seem to be a way to hook in to
I tried using both the My current implementation just has a scattering of
|
Beta Was this translation helpful? Give feedback.
-
The problem with state syncing of any kind is the following:
--> the effect or callback or whatever syncs the state runs again, and overwrites the user selection. That's bad. This might not be an issue because you only want the pre-selection if there is only one car (and the user can't select anything else, coincidentally), but it's still generally not a good pattern. The idea is, and I've written about this a lot already, to keep server and client state separated:
I've applied the concept of deriving that final selection to your sandbox: https://codesandbox.io/s/awesome-firefly-4msvmr?file=/src/App.js |
Beta Was this translation helpful? Give feedback.
-
Thank you so much @TkDodo |
Beta Was this translation helpful? Give feedback.
The problem with state syncing of any kind is the following:
--> the effect or callback or whatever syncs the state runs again, and overwrites the user selection.
That's bad.
This might not be an issue because you only want the pre-selection if there is only one car (and the user can't select anything else, coincidentally), but it's still generally not a good pattern.
The idea is, and I've written about this a lot already, to keep server and client state separated: