{"action":"closed","issue":{"url":"https://api.github.com/repos/vuejs/vuex/issues/107","repository_url":"https://api.github.com/repos/vuejs/vuex","labels_url":"https://api.github.com/repos/vuejs/vuex/issues/107/labels{/name}","comments_url":"https://api.github.com/repos/vuejs/vuex/issues/107/comments","events_url":"https://api.github.com/repos/vuejs/vuex/issues/107/events","html_url":"https://github.com/vuejs/vuex/issues/107","id":141889117,"number":107,"title":"Dispatch mutation from middleware onInit","user":{"login":"perkola","id":4265109,"avatar_url":"https://avatars.githubusercontent.com/u/4265109?v=3","gravatar_id":"","url":"https://api.github.com/users/perkola","html_url":"https://github.com/perkola","followers_url":"https://api.github.com/users/perkola/followers","following_url":"https://api.github.com/users/perkola/following{/other_user}","gists_url":"https://api.github.com/users/perkola/gists{/gist_id}","starred_url":"https://api.github.com/users/perkola/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/perkola/subscriptions","organizations_url":"https://api.github.com/users/perkola/orgs","repos_url":"https://api.github.com/users/perkola/repos","events_url":"https://api.github.com/users/perkola/events{/privacy}","received_events_url":"https://api.github.com/users/perkola/received_events","type":"User","site_admin":false},"labels":[],"state":"closed","locked":false,"assignee":null,"milestone":null,"comments":4,"created_at":"2016-03-18T14:55:20Z","updated_at":"2016-03-21T08:22:26Z","closed_at":"2016-03-21T08:22:26Z","body":"How do I dispatch a mutation from within the `onInit` function inside a middleware attached to the store?\r\n\r\nI have a module, `auth`, which contain a mutation `AUTHENTICATE` which I would like to trigger `onInit` if there is a user cookie in storage. See full code below.\r\n\r\n```\r\n// store.js\r\nconst localStorageMiddleware = {\r\n    onInit (state) {\r\n        // if user cookie in storage, dispatch mutation\r\n    }\r\n}\r\n\r\nexport default new Vuex.Store({\r\n    modules: {\r\n        auth\r\n    },\r\n    middlewares: [localStorageMiddleware]\r\n})\r\n```\r\n```\r\n// auth.js\r\nimport {\r\n    AUTHENTICATE\r\n} from '../mutation-types'\r\n\r\nconst state = {\r\n    authenticated: false\r\n}\r\n\r\nconst mutations = {\r\n    [AUTHENTICATE] (state) {\r\n        state.authenticated = true\r\n    }\r\n}\r\n\r\nexport default {\r\n    state,\r\n    mutations\r\n}\r\n```\r\nAccording to the docs, mutating the state directly is regarded as bad practise."}}