5/3/2023 0 Comments Github ebay watcherWhile consuming the API makes sense to me, how to write this module is where I'm tripping over myself. This is just the first thing that came to my head as far as an API goes. Here's a brainstorm of what it might be like to consume such a module: I want to modularize the boilerplate bit but as I start trying to think about it my mind gets boggled about how to maintain the rigid type structures behind the scenes. It works great but it's not very DRY and any change to the boilerplate obviously has to be propagated to every single hook. Well we use these hooks a lot so we are copying and pasting them into various modules in our project. Okay so what you might notice is that the bottom half of the code snippet is boilerplate. Here's a typescript playground if you wanna mess with it (go to line 65 to tinker with making dispatch calls) The first argument only accepts valid actions from Actions keys and the second argument is either not allowed in the case of the Actions type being null or is forced to conform to the Actions type specified. The dispatch function that consumers of this hook use is almost impossible to misuse.The actionHandlers object must have a handler for each action defined on Actions and the handler functions have to conform exactly, receiving the state object as the first argument, and the second argument being a data object that matches the relevant type value on Actions.The Actions type defines actions that are available to be dispatched and the type of each key is the type that is used to enforce the second argument to our dispatch function.The type of initialState is inferred from its structure so when copying this code to make a new state container hook you don't have to write a State type and then also a default state object. ![]() What's cool about it is that the state and dispatch functions are very rigidly typed. ![]() : Actions extends null ? (state: State) => Partial | void : (state: State, data: Actions) => Partial | void * You do not need to modify anything below this. There must be a handler for each action listed above.Įxport const useMyState = useContextState Specify "null" if action requires no data. Available actions and the data they require. Make sure your values have explicit types set.
0 Comments
Leave a Reply. |