TypeError: Cannot read property 'commit' of undefined - laravel

Please help me this problem, I'm doing on vue js v2 and i also new beginner but I have some issue with cannot read commit. When I login and redirect to my dashbaord by protect route
Can anyone help me?
store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state:{
authenticated: false
},
mutations: {
setAuthentication(state, status){
state.authenticated = status
}
},
})
export default store
method
methods: {
login(){
axios.post('/api/v1/login', this.form)
.then(response =>{
// this.$router.push('dashboard')
this.$store.commit('setAuthentication', true);
this.$router.replace({name: 'dashboard'})
})
}
}

try
$store.commit('{fileName}/{mutatorName}', value);
in your case
$store.commit('store/setAuthentication', true);

Try this one.
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state : {
authenticated: false,
},
mutations: {
setAuthentication(state, data) {
state.authenticated= data;
},
},
})
this.$store.commit('setAuthentication',true);

Related

Cannot access state by getters vuex vuejs

I am new to vuex I want to access user object that is inside in state by the getters getUser() method, I tried to call this
console.log(this.$store.getters.getUser); in mounted method but no results.
I tried to console log inside mutations and it return the user object.
I also followed documentations and googled the solutions but nothing happen
What else am I missing?
store.js
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
user: {},
},
getters: {
getUser: state => {
return state.user
}
},
mutations: {
auth_user(state,data) {
state.user = data
}
},
actions: {
fetchAuthUser(context){
axios.get('/user-data').then(response => {
context.commit("auth_user",response.data)
}).catch({});
}
},
})
export default store
Index.js
mounted(){
// this.auth_user;
this.getCategories();
this.$store.dispatch('fetchAuthUser', this.auth_user);
console.log(this.$store.getters.getUser);
},
Your action is async and should return a promise.
fetchAuthUser(context){
return axios.get('/user-data').then(response => {
context.commit("auth_user",response.data)
}).catch({});
}
In your mounted you can use then to handle data.
mounted(){
// this.auth_user;
this.getCategories();
this.$store.dispatch('fetchAuthUser', this.auth_user).then(() => {
console.log(this.$store.getters.getUser);
});
}

Vuex-ORM GraphQL installation troubles

I installed the Vuex-ORM Graphql Plugin into an existing Nuxt project with Laravel/GraphQL API, so that I could try avoiding using the Apollo Cache. In one of my components though, I'm running:
<script>
import Notification from '~/data/models/notification';
export default {
computed: {
notifications: () => Notification.all()
},
async mounted () {
await Notification.fetch();
}
}
</script>
however I'm receiving the error [vuex] unknown action type: entities/notifications/fetch.
I looked through the debug log and found several available getters (entities/notifications/query, entities/notifications/all, entities/notifications/find, and entities/notifications/findIn). I tried running await Notification.all() in the mounted method which removed the error, however looking in Vuex the Notifications data object is empty.
Here is the rest of my setup:
nuxt.config.js
plugins: [
'~/plugins/vuex-orm',
'~/plugins/graphql'
],
plugins/vuex-orm.js
import VuexORM from '#vuex-orm/core';
import database from '~/data/database';
export default ({ store }) => {
VuexORM.install(database)(store);
};
plugins/graphql.js
/* eslint-disable import/no-named-as-default-member */
import VuexORM from '#vuex-orm/core';
import VuexORMGraphQL from '#vuex-orm/plugin-graphql';
import { HttpLink } from 'apollo-link-http';
import fetch from 'node-fetch';
import CustomAdapter from '~/data/adapter';
import database from '~/data/database';
// The url can be anything, in this example we use the value from dotenv
export default function ({ app, env }) {
const apolloClient = app?.apolloProvider?.defaultClient;
const options = {
adapter: new CustomAdapter(),
database,
url: env.NUXT_ENV_BACKEND_API_URL,
debug: process.env.NODE_ENV !== 'production'
};
if (apolloClient) {
options.apolloClient = apolloClient;
} else {
options.link = new HttpLink({ uri: options.url, fetch });
}
VuexORM.use(VuexORMGraphQL, options);
};
/data/adapter.js
import { DefaultAdapter, ConnectionMode, ArgumentMode } from '#vuex-orm/plugin-graphql';
export default class CustomAdapter extends DefaultAdapter {
getConnectionMode () {
return ConnectionMode.PLAIN;
}
getArgumentMode () {
return ArgumentMode.LIST;
}
};
/data/database.js
import { Database } from '#vuex-orm/core';
// import models
import Notification from '~/data/models/notification';
import User from '~/data/models/user';
const database = new Database();
database.register(User);
database.register(Notification);
export default database;
/data/models/user.js
import { Model } from '#vuex-orm/core';
import Notification from './notification';
export default class User extends Model {
static entity = 'users';
static eagerLoad = ['notifications'];
static fields () {
return {
id: this.attr(null),
email: this.string(''),
first_name: this.string(''),
last_name: this.string(''),
// relationships
notifications: this.hasMany(Notification, 'user_id')
};
}
};
/data/models/notification.js
import { Model } from '#vuex-orm/core';
import User from './user';
export default class Notification extends Model {
static entity = 'notifications';
static fields () {
return {
id: this.attr(null),
message: this.string(''),
viewed: this.boolean(false),
// relationships
user: this.belongsTo(User, 'user_id')
};
}
};
package.json
"#vuex-orm/plugin-graphql": "^1.0.0-rc.41"
So in a Hail Mary throw to get this working, I ended up making a couple of changes that actually worked!
If other people come across this having similar issues, here's what I did...
In my nuxt.config.js, swapped the order of the two plugins to this:
plugins: [
'~/plugins/graphql',
'~/plugins/vuex-orm',
],
In my graphql.js plugin, I rearranged the order of the options to this (database first, followed by adapter):
const options = {
database,
adapter: new CustomAdapter(),
url: env.NUXT_ENV_BACKEND_API_URL,
debug: process.env.NODE_ENV !== 'production'
};

Vue.js - Error : Uncaught ReferenceError: getters is not defined

When I run the project, it displays ReferenceError: getters is not defined as per following image:
app.js file:
store.js file:
What is problem causing this error?
Thanks.
You should use store.getters.variable_name to retrieve state value.
Sample code for retrieving accessToken:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
accessToken: null
},
getters: {
accessToken: state => state.accessToken
},
actions: {
doSomethingsHere({ commit }, somethingData) {
console.log('accessToken: ' + store.getters.accessToken)
}
}
})
export default store

How to set value in component from ajax request to parameters during creation in Vue?

I am learning Vue and trying to set one value in component during its creation from one Ajax request.
Here is the structure of src folder:
src
assets
components
Management.vue
router
index.js
vuex
modules
caseSuiteList.js
index.js
actions.js
getters.js
App.vue
main.js
Management.vue:
<template>
</template>
<script>
import {mapState} from 'vuex'
import store from 'vuex'
export default {
name: "Management",
computed: mapState({
suite_list: state => state.caseSuiteList.suite_list
}),
created(){
store.dispatch('refresh')
}
}
</script>
caseSuiteList.js:
import axios from 'axios'
const state = {
suite_list : {}
}
const mutations = {
refreshSuiteList(state, payload) {
state.suite_list = payload
}
}
const actions = {
refresh (context) {
axios.get('http://127.0.0.1:8601/haha').then(function(res){
console.log(res.data);
context.commit('refreshSuiteList', res.data);
}
});
}
}
export default {
state,
mutations,
actions
}
How to dispatch action of caseSuiteList.js in created() of Management.vue to make this happen?
Within the vue instance (or any component within) you access the store with this.$store.
Try dispatching in the created hook of your component.
created() {
this.$store.dispatch('refresh');
}
More information about Vuex: https://vuex.vuejs.org/guide/actions.html

Vue.js Google / Microsoftgraph login

I have a Laravel app and I am using vue.js and vue-authenticate to have a user login with their Microsoft account. The vue.js app is living under a laravel route not Laravel home page i.e. if the homepage route is / then the vueapp route is /vueapp.
On the vueapp's home page I have the Login with Microsoft button configured. In my vue app the base url is set to mydomain/vueapp. I can successfully authorize the app with my Microsoft account but then instead of being able to see a success message and a token, I see the following error:
Error: Request failed with status code 405
I have Axios and Vuex installed and my vue routes are supported in the hash mode instead of history because of some weird laravel issue.
Update: I am seeing a similar issue with Google. It seems like something happens when the URI is redirected.
Update: Below is my code:
For my component:
<script>
import store from '../store'
import axios from 'axios'
export default{
data () {
return {
}
},
methods: {
authenticate: function (provider) {
console.log("Login Started" + provider);
this.$auth.authenticate(provider).then((response) => {
console.log("Login Successful " + response);
}).catch(error => {
console.log("error occured ");
console.log(error);
})
}
},
}
</script>
My HTML ---
auth Live
auth Google
In my app.js
import Vue from 'vue'
import lodash from 'lodash'
import VueLodash from 'vue-lodash'
import VueAxios from 'vue-axios'
import VueAuthenticate from 'vue-authenticate'
import Vuex from 'vuex'
import App from './App.vue'
import router from './router'
import axios from 'axios'
Vue.use(VueLodash, lodash)
Vue.use(require('vue-moment'));
import vmodal from 'vue-js-modal'
Vue.use(vmodal, {
dialog: true,
dynamic: true,
})
import Toasted from 'vue-toasted';
Vue.use(Toasted, 'top-center')
Vue.use(VueAxios, axios)
Vue.use(Vuex)
import VueAuthenticate from 'vue-authenticate'
Vue.use(VueAuthenticate, {
baseUrl: 'https://www.mywebsite.com', // Your API domain
providers: {
live: {
clientId: 'My Mcirosoft key',
redirectUri: 'https://www.mywebsite.com/auth/live' // Your client app URL
},
google: {
clientId: 'mygooglekey.apps.googleusercontent.com',
redirectUri: 'https://www.mywebsite.com/auth/google'
}
}
})
In laravel - I have the following routes. Webapp is the folder where vue app lives and it uses the hash mode for routing not history.
Route::get('webapp/{path?}', function () {
return View::make('app');
})->where( 'path', '([A-z\d-\/_.]+)?' );
Route::get('auth/live', function () {
return View::make('app');
});
Route::get('auth/google', function () {
return View::make('app');
});

Resources