Skip to content

Add a useModule composable #1826

Closed
Closed
@petervmeijgaard

Description

@petervmeijgaard

What problem does this feature solve?

Currently, the only way to use the store using the composition API is by creating a store with useStore. Using modules this way, results in messier code than it should be. I would like to introduce a useModule hook, which will export commit, dispatch, getters and state the same way as useStore does.

What does the proposed API look like?

Basic example

Current situation

// useAuth.js
import { useStore } from 'vuex';

export const useAuth = () => {
  const store = useStore();
  const isAuthenticated = computed(() => store.state.auth.isAuthenticated));
  const login = (payload) => {
    store.commit('auth/login', payload);
  };
  const logout = () => {
    store.dispatch('auth/logout');
  };

  export const {
    isAuthenticated,
    login,
    logout,
  };
};

Proposed situation:

// useAuth.js
import { useModule } from 'vuex';

export const useAuth = () => {
  const auth = useModule('auth');
  const isAuthenticated = computed(() => auth.state.isAuthenticated));
  const login = (payload) => {
    auth.commit('login', payload);
  };
  const logout = () => {
    auth.dispatch('logout');
  };

  export const {
    isAuthenticated,
    login,
    logout,
  };
};

Multiple store modules with nested modules

Current situation:

// useAuth.js
import { useModule } from 'vuex';

export const useAuth = () => {
  const store = useStore();

  const isAuthenticated = computed(() => store.state.auth.isAuthenticated);
  const myDetailsInformation = computed(() => store.state.account.myDetails.information);

  const login = async (payload) => {
    await auth.dispatch('auth/login', payload);
    await myDetails.dispatch('account/my-details/fetch-information');
  };
  const logout = () => {
    store.commit('logout');
  };

  export const {
    isAuthenticated,
    myDetailsInformation,
    login,
    logout,
  };
};

Proposed situation:

// useAuth.js
import { useModule } from 'vuex';

export const useAuth = () => {
  const auth = useModule('auth');
  const myDetails = useModule('account/my-details');

  const isAuthenticated = computed(() => auth.state.isAuthenticated);
  const myDetailsInformation = computed(() => myDetails.state.information);

  const login = async (payload) => {
    await auth.dispatch('login', payload);
    await myDetails.dispatch('fetch-information');
  };
  const logout = () => {
    store.commit('logout');
  };

  export const {
    isAuthenticated,
    myDetailsInformation,
    login,
    logout,
  };
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions