Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using namespaced mutations outside components with Nuxt #48

Open
mirabledictu opened this issue Aug 8, 2021 · 2 comments
Open

Using namespaced mutations outside components with Nuxt #48

mirabledictu opened this issue Aug 8, 2021 · 2 comments

Comments

@mirabledictu
Copy link

mirabledictu commented Aug 8, 2021

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
Copy link
Author

hi

@davidmeirlevy
Copy link
Contributor

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants