-
Notifications
You must be signed in to change notification settings - Fork 0
useStore
Convenience function to create a Store. Multiple options can be provided, see StoreOptions.
function useStore<T>(state: T, options?: StoreOptions<T>): Pointer;Unless the override option is set to true, this function will NOT override an existing store, it is therefore safe to use to make sure a store exists, and can be use to access the same store accross multiple components.
- The
statepassed in the function is used to give the store an initial state if it does not already exists. Therefore, the first invocation ofuseStoresets the initial state for the store. If multiple components useuseStore, the first rendered component will set the initial state of the store. - If no pointer is provided, a pointer will be assigned and returned.
state: T
The initial state of the store. If the store already exists, the state will NOT be overriden by default, unless the
overrideoption is set totrue
options?: StoreOptions<T>
See
StoreOptions
Pointer
A memory address to access the store. If a pointer is provided in the
StoreOptions, it will return the same pointer, if not, it will allocate a pointer and return it.
// 1. Creating a store without any options
const store1Ptr = useStore(0);
console.log(Stores.get<number>(store1Ptr).state); // Output: 0
// 2. Creating a store with options
const store2Ptr = Store.newPointer();
useStore(0, { pointer: store2Ptr, onChange: (state) => console.log(state), });
console.log(Stores.get<number>(store2Ptr).state); // Ouput: 0
Stores.get<number>(store2Ptr).set((prevState) => prevState + 1); // Ouput: 1Multiple options can be passed to useStore. This interface is a template for all options that can be provided.
interface StoreOptions <T> {
errorHandling?: StoreOptionsErrorHandling;
observers?: Observer<T>[];
onChange?: (state: T) => void;
override?: boolean;
pointer?: Pointer;
}- T
Any serializable type. Must match
Storetype.