Refactoring Context to Zustand - How can I initialize a store property with a hook call? #1027
-
I developed a useOauth2 hook where I pass in some env configuration and it gives me back some auth related functions and components: { Callback, login, logout, ...}. I store this in a Context and it's available as I need it:
So I had a bunch of Contexts including this one wrapping my App, and I've been refactoring to use Zustand, but the auth property has to be initialized in a functional component, or you get 'Error: Invalid hook call'. I could create a setter and initialize it from a component, but it would render uninitialized the first time through, then call the useEffect to initialize, and I would have to do some refactoring to check that the items were initialized before using, which I don't like as much as the Context where they're immediately available. Is there another way to get this initialized on the store? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 5 replies
-
I would also like to hear from others how they use zustand store for auth state. From the lib perspective, what you are trying to has a mismatch.
You could, however, create a zustand store in a component (instead of at module level): https://github.com/pmndrs/zustand#react-context
It's probably unavoidable if you need to use |
Beta Was this translation helpful? Give feedback.
-
@jestrickler Came across almost similar problem. How did you manage to fix this issue gracefully? Is there any good way to do it? |
Beta Was this translation helpful? Give feedback.
I would also like to hear from others how they use zustand store for auth state.
From the lib perspective, what you are trying to has a mismatch.
useOauth2 provides a state and AuthContext provides a dependency injection.
So you can't use zustand store only to replace AuthContext. You want to replace both useOauth2 and AuthContext altogether. oauth2 should have a vanilla (non-react) api.
You could, however, create a zustand store in a component (instead of at module level): https://github.com/pmndrs/zustand#react-context
It's probably unavoidable if you need to use
useOa…