Cannot access state by getters vuex vuejs - laravel

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);
});
}

Related

Vuex get data via slim (Ruby on rails)

How to transfer data if I receive an array via Slim?
regions-list :region=#regions
regions-list - my component vue
:region - array with items
#regions - variable with items from backend
Im new with vuex, i think, i need something like this, but don’t know how to convey array with items
This is how you can organize the work of Vuex
export default new Vuex.Store({
state: {
reactions: [],
},
mutations: {
setReactions(state, segment) {
state.reactions = segment;
},
},
actions: {
async loadReactions({ commit }) {
try {
const reactions = '... response/request';
commit('setReactions', reactions); // Here we use mutation to put new data into state.
} catch (e) {
// ...
}
},
},
});
In your component vue regions-list
<template>
<div>{{ reactions }}</div> <!-- Here you can display and look at the content -->
</template>
<script>
import { mapState, mapActions } from 'vuex';
export default {
name: 'RegionsList',
computed: {
...mapState(['reactions']), // This is get the state
},
created() {
this.loadReactions(); // Here you perform a function that receives data and puts it in state
},
methods: {
...mapActions(['loadReactions']),
},
};
</script>
<style scoped></style>

TypeError: Cannot read property 'commit' of undefined

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

Data not showing on vue.js component using laravel api

I'm trying to get the data from database using an API, but there are no output on my vue controller.
Am I doing this right?
I think I'm assigning the scheduleList the wrong way.
I'm very new to vue.js and API, I want to know what I'm doing wrong here.
Controller
public function schedules(){
return Schedule::all();
}
api.php
Route::get('schedules', 'CalendarController#schedules');
Vue Component
<script>
import axios from 'axios'
export default {
data() {
return {
schedules: [],
scheduleList: [
{
id: schedules.id,
title: schedules.title,
category: schedules.category,
start: schedules.start,
end: schedules.end
},
],
};
},
methods: {
loadSchedules() {
axios.get('/api/schedules')
.then((response) => {
this.schedules = response.data;
})
}
},
mounted() {
this.loadSchedules();
}
};
</script>
<style>
</style>
The issue is in your data option because you're referencing schedules which is undefined, I'm sure that you're meaning this.schedules but doing that will not solve the issue because at first rendering this.schedules is an empty array, another problem that you're referencing at as object in scheduleList items using schedules.id, if the schedules property is an array i recommend the following solution :
<script>
import axios from 'axios'
export default {
data() {
return {
schedules: [],
scheduleList: [],
};
},
methods: {
loadSchedules() {
axios.get('/api/schedules')
.then((response) => {
this.schedules = response.data;
let schedule=this.schedules[0]
this.scheduleList.push({
id: schedule.id,
title: schedule.title,
category: schedule.category,
start: schedule.start,
end: schedule.end
})
})
}
},
mounted() {
this.loadSchedules();
}
};
</script>
always catch errors if you do promises.
loadSchedules() {
axios.get('/api/schedules')
.then((response) => {
this.schedules = response.data;
})
.catch(error => {
console.log(error)
})
inside your error you can better see whats going wrong.
other way is the "network" tab in your browser where you can trace your api request

admin-on-rest / restClient : call a resource with no auth

I made a register page that use restClient to send a POST to /users api.
But my problem is that the only way to send a POST is to be logged first as I receive this error log from the restClient :
'Could not find stored JWT and no authentication strategy was given'
Is there a way to desactivate the authentication middleware for a specific api call ?
// registerActions.js
import { CREATE } from 'admin-on-rest'
export const USER_REGISTER = 'AOR/USER_REGISTER'
export const USER_REGISTER_LOADING = 'AOR/USER_REGISTER_LOADING'
export const USER_REGISTER_FAILURE = 'AOR/USER_REGISTER_FAILURE'
export const USER_REGISTER_SUCCESS = 'AOR/USER_REGISTER_SUCCESS'
export const userRegister = (data, basePath) => ({
type: USER_REGISTER,
payload: { data: { email: data.username, ...data } },
meta: { resource: 'users', fetch: CREATE, auth: true },
})
//registerSaga.js
import { put, takeEvery, all } from 'redux-saga/effects'
import { push } from 'react-router-redux'
import { showNotification } from 'admin-on-rest'
import {
USER_REGISTER,
USER_REGISTER_LOADING,
USER_REGISTER_SUCCESS,
USER_REGISTER_FAILURE
} from './registerActions'
function* registerSuccess() {
yield put(showNotification('Register approved'))
yield put(push('/'))
}
function* registerFailure({ error }) {
yield put(showNotification('Error: register not approved', 'warning'))
console.error(error)
}
export default function* commentSaga() {
yield all([
takeEvery(USER_REGISTER_SUCCESS, registerSuccess),
takeEvery(USER_REGISTER_FAILURE, registerFailure),
])
}
You'll probably have to make your own feathers client and explicitly bypass the call to authenticate for this specific request
You can also write a rest wrappper this will intercept the call for this particular case and bypass auth
https://marmelab.com/admin-on-rest/RestClients.html#decorating-your-rest-client-example-of-file-upload
So something like below
const restWrapper = requestHandler => (type, resource, params) => {
import { fetchUtils } from 'admin-on-rest';
if (type === 'CREATE' && resource === 'users') {
return fetchUtils.fetchJson(url, params)
.then((response) => {
const {json} = response;
return { data: json };
})
}
Eliminates the need of rewriting an entire Rest Client when you only want to override the default behaviour for a single case

Show authenticated user in vuejs

I've tried to follow the following tutorial in laravel 5.3 and vue 2.0:
https://www.youtube.com/watch?v=CeXDx4hdT1s
Products.vue:
<my-product :key="product.id"
v-for="product in products"
:authenticatedUser="authenticatedUser"
:product="product">
...
computed: {
authenticatedUser() {
this.$auth.getAuthenticatedUser()
}
},
Product.vue:
export default{
props: ['product', 'authenticatedUser']
}
Auth.js
setAuthenticatedUser(data){
authenticatedUser = data;
},
getAuthenticatedUser(){
return authenticatedUser;
}
Navbar.vue:
export default {
data() {
return {
isAuth: null
}
},
created() {
this.isAuth = this.$auth.isAuthenticated();
this.setAuthenticatedUser();
},
methods: {
setAuthenticatedUser() {
this.$http.get('api/user')
.then(response => {
this.$auth.setAuthenticatedUser(response.body);
console.log(this.$auth.getAuthenticatedUser());
})
}
}
I try to pass the authenticated user which is called in the Products.vue within the Product.vue
For that, at each login, the setAuthenticated method in the Navbar.vue is called where the authenticated user should be set in the corresponding method.
But when I check the property in the debugger of the browser, it's written Props authenticatedUser: undefinded. In fact the authenticated user is not shown.
Any ideas what it's missing?
In computed you need to return the value you want the property to take.
It should be:
computed: {
authenticatedUser() {
return this.$auth.getAuthenticatedUser()
}
},

Resources