Skip to content

Commit

Permalink
feat: add useStaticStore and getStore
Browse files Browse the repository at this point in the history
  • Loading branch information
mychidarko committed Nov 20, 2023
1 parent 016258d commit 0931b22
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 10 deletions.
31 changes: 22 additions & 9 deletions packages/store/src/core/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,15 +53,24 @@ export function useStaticStore<StateType = any>(
export function useStaticStore<StateType = any>(
item?: string
): [StateType, SetStoreFn<StateType>] {
return [
Manager.get(item),
function (state: SetStateAction<StateType>) {
const newState: any = Manager.get();
newState[item as any] = state;

Manager.set(newState);
},
];
const stateSetter: SetStoreFn<StateType> = (value) => {
let stateValue: State = value as State;
let stateToSet = stateValue;

if (typeof value === 'function') {
const callableState = value as (prevState: StateType) => State;
stateValue = callableState(Manager.get(item));
}

if (item) {
stateToSet = { [item]: stateValue };
}

Manager.set(stateToSet);
Manager.applyPluginHook('onSave', Manager.get());
};

return [Manager.get(item), stateSetter];
}

export function useReducer<PayloadType = any>(
Expand All @@ -75,3 +84,7 @@ export function setStore<StateType extends State = State>(
) {
return Manager.set(item);
}

export function getStore<StateType = any>(item?: string): StateType {
return Manager.get(item);
}
9 changes: 8 additions & 1 deletion packages/store/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
export * from './@types';
export * from './plugins/';

export { createStore, useStore, setStore, useReducer } from './core/hooks';
export {
createStore,
useStore,
useStaticStore,
setStore,
getStore,
useReducer,
} from './core/hooks';

0 comments on commit 0931b22

Please sign in to comment.