How to address state with optional fields when overwriting? #2610
Unanswered
thepuzzlemaster
asked this question in
Q&A
Replies: 2 comments 1 reply
-
That sounds a little bit tricky. I think you need |
Beta Was this translation helpful? Give feedback.
0 replies
-
Thanks for the quick reply. If there's no sort of built-in way to accomplish this, I did come up with the following solution which looks like it will work, based on your suggestion.
I'm not sure if I like this more than just ensuring that my Thanks. |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I have a state that looks like this:
My actions look like this:
My default state looks like this:
I'm using zustand in a nextjs application and my store looks like this:
The issue is that I want to be able to clear out my state and reset it back to the defaultInitState with the potential for some overrides. Or another way to think about it, is that I want to be able to set 1 or more fields, and use the
defaultInitState
for any fields I don't include. But if I callmyState.setFields({})
, because of the shallow merge, it never overwrites any of the existing optional fields. If I change mysetFields()
action to usereplace
, then it overwrites all my actions.Some possible options I've considered:
Separate the actions outside of the createStore function and then include them in my actual setter, but I both don't love the idea of that, and also haven't figured out if there's a syntax for that in typescript because
set
isn't available outside of the createStore context.Another possibility is to make sure I explicitly include all fields in the
defaultInitState
, even ones which may have an undefined value. I don't love this idea because if I ever forget to include a field, its value won't be cleared out when callingsetFields
if it already has a value. I also don't love the idea of needing extra lines of code - unnecessarily.Am I missing something obvious here? Or is there another potential approach I'm not thinking of? I've looked through a bunch of searches for this sort of thing, but haven't quite found a good answer.
Beta Was this translation helpful? Give feedback.
All reactions