You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Hi! In my company we use contexts widely, and for most of them we expect them to be mounted in the root store (if not, we want things to crash as soon as possible). This is how we define and use them:
constsomeContext=createContext<SomeType>()// At initializationsomeContext.setComputed(()=>createSomeValue())// In a store:constvalue=someContext.get(this)if(!value)thrownewError("Missing value")// ...
This check helps us to guarantee that the context has a value, and makes TypeScript happy.
But it's quite verbose, and a use case we have in many places. So we created a tiny helper to create a context that must receive a value:
constcreateRequiredContext=<T>()=>{constctx=createContext<T>()asContext<T>ctx.setDefaultComputed(()=>{thrownewError("Missing value for context")})returnctx}
The code becomes a bit more concise as there is not need to check the returned value anymore:
constsomeContext=createRequiredContext<SomeType>()// At initializationsomeContext.setComputed(()=>createSomeValue())// In a store:constvalue=someContext.get(this)// No need to check, value is guaranteed to be defined :)
Just thought it could help other users. If such a helper could be in the lib (or even be part of the context API), it would be terrific 😉.
Thanks for all the work 👍
The text was updated successfully, but these errors were encountered:
I'm torn. One the one hand I see its usefulness, but on the other hand it worries me it might crash reactions such as
reaction(() => someContext.get(someNode), ...)
in unexpected ways.
For example, given the node gets detached from the root store:
a) in the case of "createContext" it will return undefined, which TS should warn about due to it being undefined in the type itself
b) with "createRequiredContext" that piece of code would throw, but nothing would warn the programmer about it, which could be kind of unexpected.
Hi! In my company we use contexts widely, and for most of them we expect them to be mounted in the root store (if not, we want things to crash as soon as possible). This is how we define and use them:
This check helps us to guarantee that the context has a value, and makes TypeScript happy.
But it's quite verbose, and a use case we have in many places. So we created a tiny helper to create a context that must receive a value:
The code becomes a bit more concise as there is not need to check the returned value anymore:
Just thought it could help other users. If such a helper could be in the lib (or even be part of the context API), it would be terrific 😉.
Thanks for all the work 👍
The text was updated successfully, but these errors were encountered: