zustandjs / zustand-slices

A slice utility for Zustand
MIT License
185 stars 8 forks source link

Feature request: Initialize StoreProvider with defaultState #27

Open Christopher96u opened 1 month ago

Christopher96u commented 1 month ago

I'm trying to implement something like this library: https://github.com/charkour/zustand-di

I'm using the utility helper from this library(zustand-slices) to create the Provider, but I'm still dealing with the TS Type inference to make it type-safe.

Could you provide a example of this feature?

It's really helpful for testing. I don't wanna use stores without Provider because it's really hard to test.

Any idea?

I want to get the Provider like this

<GlobalStoreProvider defaultState={initialState}> where initialState infers the type based on my store, thanks!

dai-shi commented 1 month ago

If I understand it correctly, the question is about how to type React Context, which is not specific to Zustand.

How does zustand-di solve it?

Please try to create a very very small example to illustrate what you would like to accomplish with https://www.typescriptlang.org/play.

Christopher96u commented 1 month ago

Hi, a bit busy with my little one today. I'll make a demo tonight and share it with you. Thanks

Christopher96u commented 1 month ago

Hi @dai-shi , I've written an example and added some comments. example

I'm open to any suggestion. I feel adding the ability to define the zustand context with a prop initialState would be helpful for testing and test components in a isolated way. I'm doing this workaround because I have the same tradeoff than the blogger from here blog . Initialize the store with context will save lot of effors. If not, any advice? The Zustand official documentation for testing, doesn't explain it very well. Thanks

dai-shi commented 1 month ago

Unfortunately, the example doesn't help me understand the problem. Is it modified after you created?

I have a few comments: