Less verbose selectors? #582
-
So the documentation suggests we do this: const { nuts, honey } = useStore(state => ({ nuts: state.nuts, honey: state.honey }), shallow) And I guess a slightly shorter version would be: const { nuts, honey } = useStore(({ nuts, honey }) => ({ nuts, honey }), shallow) But is there any other way to do this that doesn't require writing the same property name 3 times? I want to move away from Context and put some setter functions here but I feel like there should be a better way. If I have 4-5 setters and each component takes a different combination of them I end up having to write a bunch of code only to get the functions into my component. |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments 10 replies
-
Hi, this is an interesting discussion. Hope someone will jump in. If I were to write such an example, I would do: const nuts = useStore(state => state.nuts)
const honey = useStore(state => state.honey) Or, I'd use valtio instead. |
Beta Was this translation helpful? Give feedback.
-
i usually group stuff in the state model. if i know that props belong together and wont cause perf issues i just go const { nuts, honey } = useStore(state => state.food) |
Beta Was this translation helpful? Give feedback.
-
const { nuts, honey } = useStore(null, shallow)
const { nuts, honey } = useStore(s => s, shallow) Ideally this would work |
Beta Was this translation helpful? Give feedback.
-
I came up with this solution:
Thanks to those functions, you can then simply access your store like this:
Note that it is Typescript compliant, so those strings are type safe. I have a running example there: |
Beta Was this translation helpful? Give feedback.
-
For what it's worth, I also feel this issue. As a somewhat concrete example, it's pretty easy to accidentally do something like this, especially when you have a lot of picks going on all over the place: const boolA = useStore(s => s.boolA);
const boolB = useStore(s => s.boolA); // BUG!!!
const boolC = useStore(s => s.boolC); Whereas this seems a little more dummy-proof (not to mention a little more concise), especially with TypeScript (with proper Types, you'd get an error if you repeated const {boolA, boolB, boolC} = usePartialStoreWithShallow('boolA', 'boolB', 'boolC'); There are already some decent suggestions here, but I figured I'd give a +1 to the sentiment behind the issue. |
Beta Was this translation helpful? Give feedback.
@TheTisiboth have you read this https://docs.pmnd.rs/zustand/guides/auto-generating-selectors#create-the-following-function:-createselectors