Skip to content

Commit

Permalink
feat: new approach for useStore composable
Browse files Browse the repository at this point in the history
  • Loading branch information
lauramargar committed Feb 8, 2024
1 parent 1aa1105 commit 2f224db
Showing 1 changed file with 14 additions and 14 deletions.
28 changes: 14 additions & 14 deletions packages/x-components/src/composables/use-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,34 +7,34 @@ import { ExtractState, XModuleName } from '../x-modules/x-modules.types';
* Function which returns the `$store` object from the current component instance
* and the selected state as a dictionary of paths.
*
* @param module - The {@link XModuleName} of the getter.
* @returns The state properties of the module and the `$store`.
*
* @public
*/
export function useStore<Module extends XModuleName, Path extends keyof ExtractState<Module>>(
module?: Module
): UseStore<Module, Path> {
export function useStore(): UseStore {
const store = (getCurrentInstance()?.proxy as { $store: Store<any> }).$store;
const useState = (module: Module, paths: Path[]): ComputedRef<Dictionary<keyof Path>> => {
return paths.reduce<ComputedRef<Dictionary<keyof Path>>>((state, path) => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
state[path] = computed(() => store.state.x[module][path]);
const useState = <Module extends XModuleName, Paths extends keyof ExtractState<Module>>(
module: Module,
paths: Paths[]
): Dictionary<ComputedRef> => {
return paths.reduce<Dictionary<ComputedRef>>((state, path) => {
state[path as string] = computed(() => store.state.x[module][path]);
return state;
}, {} as ComputedRef<Dictionary<keyof Path>>);
}, {});
};
const useStateWithModule = useState.bind(module);
return {
store,
useState: module ? useStateWithModule : useState
useState
};
}

/**
* Return type of the {@link useStore} composable.
*/
type UseStore<Module extends XModuleName, Path extends keyof ExtractState<Module>> = {
type UseStore = {
store: Store<any>;
useState: (module: Module, paths: Path[]) => ComputedRef<Dictionary<keyof Path>>;
useState: <Module extends XModuleName, Paths extends keyof ExtractState<Module>>(
module: Module,
paths: Paths[]
) => Dictionary<ComputedRef>;
};

0 comments on commit 2f224db

Please sign in to comment.