greenpress / vuex-composition-helpers

A util package to use Vuex with Composition API easily.
https://www.npmjs.com/package/vuex-composition-helpers
MIT License
288 stars 32 forks source link

Using namespaced mutations outside components with Nuxt #48

Open mirabledictu opened 2 years ago

mirabledictu commented 2 years ago

So in the docs, you can import stores outside a component and create helpers outside of the setup method. How would someone use useMutation for example, in a Nuxt plugin?

Say you have a plugin/sample.ts

import { namespacedHelpers } from '~/store/auth';

const { useMutations } = namespacedHelpers;
const { setIsAuthenticated} = useMutations();

export default defineNuxtPlugin((context) => {
   // use setIsAuthenticated here
})

and store/auth.ts

import { MutationTree } from 'vuex';
import { createNamespacedHelpers } from 'vuex-composition-helpers';
import { User } from '~/composables';

export const state = () => ({
  isAuthenticated: false,
  user: null as null | User,
});

export type State = ReturnType<typeof state>;

export type Mutations<S = State> = {
  setIsAuthenticated(state: S, payload: boolean): void;
  setUser(state: S, payload: null | User): void;
};

export const mutations: MutationTree<State> & Mutations = {
  setIsAuthenticated: (state, payload: boolean) => {
    state.isAuthenticated = payload;
  },
  setUser: (state, payload: null | User) => {
    state.user = payload;
  },
};

export const namespacedHelpers = createNamespacedHelpers<
  State,
  {},
  {},
  Mutations
>('auth');

This throws an error: You must use this function within the "setup()" method, or insert the store as first argument. which is reasonable because it's outside the setup() method.

But what's the line saying or insert the store as first argument? I don't have a store variable that I can pass because Nuxt treats files as modules and it only exports states, mutations, getters and actions.

mirabledictu commented 2 years ago

hi

davidmeirlevy commented 2 years ago

hi,

Nuxt has a very strict behavior and trying to break that behavior will cause server memory leaks (from experience). I believe you can use a nuxt-middleware to get the store, but be careful with that solution.