What are the types for { dispatch, commit } in vuex?
Asked Answered
S

4

13

I got vujes typescript project and in vuex store i got something like:

async getUserProfile ({ dispatch, commit }: any) {}

Well i dont want any because that suck and you dont have help/autocomplete in editor. I found this import { Dispatch, Commit } from "vuex"; but how to pass that info to { dispatch, commit }: any

Situation answered 16/5, 2018 at 15:54 Comment(0)
A
20

You use ActionContext<S, R>, like Vuex does:

getUserProfile( context: ActionContext<S, R>) {}

Where S is the State and R is the RootState.

Then you call dispatch and commit off of the context:

 context.dispatch('action')
 context.commit('mutation')
Averir answered 16/5, 2018 at 17:22 Comment(1)
Is there any documentation I can refer to?Fenderson
O
17

You can check out available vuex types in this file:

node_modules/vuex/types/index.d.ts

// line 49 :

export interface Commit {
  (type: string, payload?: any, options?: CommitOptions): void;
  <P extends Payload>(payloadWithType: P, options?: CommitOptions): void;
}

you can import and use that instead of ActionContext like so:

import { Commit } from 'vuex';

const actions = {
    loadUser ({ commit }: { commit: Commit }, user: any) {
        commit('setUser', user);
    },

    ...
};

hope that helps :)

Ovary answered 1/6, 2020 at 19:19 Comment(0)
P
5

You can still destructure the context object if you'd like.

import { ActionContext } from 'vuex';
import { RootState } from './types';

const actions = {
    // destructured
    loadUser ({ commit }: ActionContext<RootState, RootState>, user: any) {
        commit('setUser', user);
    },

    // not destructured
    loadUser (context: ActionContext<RootState, RootState>, user: any) {
        context.commit('setUser', user);
    },
};
Patency answered 30/11, 2019 at 22:59 Comment(1)
ActionContext signature is ActionContext<S, R> which means first argument is module state and second is root stateCutaway
B
3

You can just import Commit type from vuex.

import { Commit } from "vuex";

and use in actions like this:

changeNumber({ commit }: { commit: Commit }, new_number: number) {
  commit("setNewNumber", new_number);
}
Baudoin answered 3/5, 2021 at 7:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.