Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork1.3k
createStoreHook helper function for @xstate/store/react#5298
Uh oh!
There was an error while loading.Please reload this page.
Uh oh!
There was an error while loading.Please reload this page.
-
Hello, I've found the DX of zustand creating a bound hook automatically for each store to be very ergonomic and pleasant. I also quite like @xstate/store and its type inference + structure around events. But I've been confused as to why I need to pass in the store as the first argument to // createSelectorHook.tsimporttype{Store}from'@xstate/store';import{useSelector}from'@xstate/store/react';/* --------------------------------------------------------- * * helpers * --------------------------------------------------------- *//** Pull the context type out of any `Store` instance */typeContextOf<TextendsStore<any,any,any>>=TextendsStore< inferCtx,any,any> ?Ctx :never;/** EqualityFn signature used by `useSelector` (first arg can be `undefined`) */typeEqualityFn<T>=(a:T|undefined,b:T)=>boolean;/* --------------------------------------------------------- * * factory * --------------------------------------------------------- *//** * Create a React hook that’s permanently bound to the given store. * *@example * export const store = createStore({ … }); * export const useStore = createSelectorHook(store); * * const count = useStore(c => c.count); // number * const name = useStore(c => c.name); // string */exportfunctioncreateSelectorHook<TStoreextendsStore<any,any,any>>(store:TStore){typeCtx=ContextOf<TStore>;returnfunctionuseStoreSelector<Selected>(selector:(ctx:Ctx)=>Selected,equalityFn?:EqualityFn<Selected>):Selected{returnuseSelector(store,(state)=>selector(state.contextasCtx),equalityFn// matches the exact signature expected by useSelector [oai_citation:0‡github.com](https://github.com/statelyai/xstate/discussions/4998?utm_source=chatgpt.com));};} |
BetaWas this translation helpful?Give feedback.
All reactions
Replies: 1 comment
-
Inspired by this, I added a proposed constuseCountStore=createStoreHook({context:{count:0},on:{inc:(ctx,event:{by:number})=>({ ...ctx,count:ctx.count+event.by})}});// UsagefunctionComponent(){const[count,store]=useCountStore((s)=>s.context.count);store.trigger.inc({by:3});// Usage (no selector)const[snapshot,store]=useCountStore();} |
BetaWas this translation helpful?Give feedback.
All reactions
🎉 1