Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 847
pregmatch Avatar asked May 16 '18 15:05

pregmatch


People also ask

What is difference between dispatch and commit in Vuex?

Dispatch triggers an action whereas commit triggers a mutation. $dispatch is always used from your methods in routes/components. It sends a message to Vuex store to perform some action. The action can be performed any time after the current tick so that it will not affect the frontend performance.

How do I dispatch an action on Vuex?

You can call another Vuex action by passing the name of that action as a string as the first argument of dispatch : const store = new Vuex. Store({ actions: { walk(context) { context. dispatch("goForward"); }, goForward(context) { // }, }, });

What is store Dispatch in Vuex?

$dispatch sends a message to your vuex store to do some action. The action may be done anytime after the current tick, so that your frontend performance is not affected. You never commit from any of your components / routes. It is done only from within an action, and only when you have some data to commit.

Is Vuex dispatch async?

To use async and await with Vuex dispatch, we can add an action method that's an async function.


2 Answers

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')
like image 115
Ohgodwhy Avatar answered Sep 22 '22 09:09

Ohgodwhy


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 :)

like image 23
coreycosman Avatar answered Sep 26 '22 09:09

coreycosman