Value of vuex getter not updating when switching between routed components - vue.js

I have a vuex getter that takes the value of an array from my state.
import Vue from 'vue'
import Vuex from 'vuex';
Vue.use(Vuex);
export const store = new Vuex.Store({
state: {
tableRow: [
{
"name": 1,
"numSongs": 2,
"Year": 3
}
]
},
getters:{
tRow : state => {
return state.tableRow
}
}
});
I have a function that takes the values from a table row and sets the value of it to my computed property for the getter.
$("#table1 tr").click(function () {
var list = [];
var $row = $(this).closest("tr"),
$tds = $row.find("td");
list.push({ name: $tds.eq(0).text(), numSongs: $tds.eq(1).text(), Year: $tds.eq(2).text() });
// self.$store.state.tableRow = list;
this.tabRow = list;
console.log(this.tabRow);
self.passData();
});
});
},
computed: {
tabRow(){
return this.$store.getters.tRow;
}
},
Then in another one of my routed components i set the same computed property and then try to call it in the template but the value it outputs is the default values i gave it.
mounted: function () {
var self = this;
console.log(this.tabRow)
// self.passedRow = self.$store.state.tableRow;
self.passedRow = this.tabRow;
this.startDoughnut(this.$refs.canvas, 'Doughnut');
},
computed: {
tabRow(){
return this.$store.getters.tRow;
}
I am not properly efficient with vuex yet so i am not sure why this won't work any help would be appreciated.

What you are trying to do here is not possible in vue compute property and also in Vuex. Computed properties and vuex getters areread only.
this.tabRow = list;
======================
computed: {
tabRow(){
return this.$store.getters.tRow;
}
Do this
computed: {
tabRow(){
get: function () {
return this.$store.getters.tRow;
},
set: function (newValue) {
commit('SET_TABLEROW', newValue)
});
}
}
In store add a mutation
mutations:{
SET_TABLEROW: (state,list) => {
state.tableRow=list
}
}
refer https://vuex.vuejs.org/en/mutations.html

I have a function that takes the values from a table row and sets the value of it to my computed property for the getter.
Examining your second block of code:
You are trying to set the value of list to the computed property tabRow. Computed properties are by default getter-only, i.e we can only get or acess a value not set a value.
As far as I understood your problem you want to take the value from the table row and add it to the tableRow property in your vuex state. For that you need a mutation
$("#table1 tr").click(function () {
var $row = $(this).closest("tr"),
$tds = $row.find("td");
var list = { name: $tds.eq(0).text(), numSongs: $tds.eq(1).text(), Year: $tds.eq(2).text() };
self.$store.commit('addTableRow', list);
self.passData();
});
In you vuex store add the mutation
import Vue from 'vue'
import Vuex from 'vuex';
Vue.use(Vuex);
export const store = new Vuex.Store({
state: {
tableRow: [
{
"name": 1,
"numSongs": 2,
"Year": 3
}
]
},
getters:{
tRow : state => {
return state.tableRow
}
},
mutations: {
addTableRow: (state, list) => {
state.tableRow.push(list);
}
}
});

Related

Vuex reference not returning correct value

I am referencing a VueX getter in a object like so :
computed : {
...mapGetters(['activeLayer']),
}
The store getter looks like this :
getters : {
activeLayer : state => state.views[state.activeView].layers[state.views[state.activeView].activeLayer]
}
I am then using a watch to monitor for changes:
created {
var that = this;
this.$store.watch( function(state) {return state.views[state.activeView].activeLayer},
function() {
console.log(that.activeLayer); // Returns initial value
that.$store.state.views[this.$store.state.activeView].layers[this.$store.state.views[this.$store.state.activeView].activeLayer]; // Returns correct value
}
,{ deep: true } )
}
The issue is that when the store changes activeLayer does not update to the new value.
How can I force activeLayer to update?
Try using mapState instead and watching for changing would be like this:
import { mapState } from 'vuex';
computed: { ...mapState(['activeLayer']), }
watch: {
activeLayer(newValue, oldValue) {
console.log(newValue);
}
},

I want to update my component's state on vuex state change

This is my task module which I am using in store. In this my showTaskInForm() function works perfectly fine. I can see the task appear in state.task through vue dev tools
const state = {
tasks: [] // array of objects
task: null
}
const getters = {
task: state => state.task
};
const actions = {
showTaskInForm({ commit, state }, taskId) {
const task = state.tasks.filter(task => task.id === taskId);
const taskToEdit = task.length === 1 && task[0];
commit('showTaskInForm', taskToEdit);
}
};
const mutations = {
showTaskInForm: (state, taskToEdit) => (state.task = taskToEdit)
}
export default {
state,
getters,
actions,
mutations
};
And this is my AddTask.vue component
import { mapActions, mapGetters } from "vuex";
export default {
name: "AddTask",
data() {
return {
taskName : this.task ? this.task.name : null,
description : this.task ? this.task.description : null,
};
},
computed: mapGetters(['task']),
};
As I mentioned earlier I can see the state.task in vuex is being filled but in my AddTask.vue component I need to make that if there is task in vuex so my form fields get the value of the state.task.
Help me please I am new to Vue.js.
The object returned by the data function in your AddTask component is evaluated only once when the component is instantiated. That means that your expressions for taskName and description won't evaluate during the life cycle of the object.
You need to model taskName and description as computed properties in order to the tertiary operator to be evaluated after the dependency changes (in your case, the value of task coming from the store).
import { mapActions, mapGetters } from "vuex";
export default {
name: "AddTask",
computed: {
...mapGetters(['task']),
taskName() {
return this.task ? this.task.name : null
},
description() {
return this.task ? this.task.description : null
}
};

VueJS How to access Mounted() variables in Methods

I'm new in Vue and would like assistance on how to access and use variables created in Mounted() in my methods.
I have this code
Template
<select class="controls" #change="getCatval()">
Script
mounted() {
var allcards = this.$refs.allcards;
var mixer = mixitup(allcards);
},
methods: {
getCatval() {
var category = event.target.value;
// I want to access mixer here;
}
}
I can't find a solution anywhere besides this example where I could call a method x from mounted() and pass mixer to it then use it inside my getCatval()
Is there an easier way to access those variables?
I will first suggest you to stop using var, and use the latest, let and const to declare variable
You have to first declare a variable in data():
data(){
return {
allcards: "",
mixer: ""
}
}
and then in your mounted():
mounted() {
this.allcards = this.$refs.allcards;
this.mixer = mixitup(this.allcards);
},
methods: {
getCatval() {
let category = event.target.value;
this.mixer
}
}
like Ninth Autumn said : object returned by the data function and props of your components are defined as attributes of the component, like your methods defined in the method attribute of a component, it's in this so you can use it everywhere in your component !
Here an example:
data() {
return {
yourVar: 'hello',
};
},
mounted() { this.sayHello(); },
method: {
sayHello() { console.log(this.yourVar); },
},
Update
you cannot pass any value outside if it's in block scope - Either you need to get it from a common place or set any common value
As I can see, var mixer = mixitup(allcards); is in the end acting as a function which does some operation with allcards passed to it and then returns a value.
1 - Place it to different helper file if mixitup is totally independent and not using any vue props used by your component
In your helper.js
const mixitup = cards => {
// Do some operation with cards
let modifiedCards = 'Hey I get returned by your function'
return modifiedCards
}
export default {
mixitup
}
And then in your vue file just import it and use it is as a method.
In yourVue.vue
import Helpers from '...path../helpers'
const mixitup = Helpers.mixitup
export default {
name: 'YourVue',
data: ...,
computed: ...,
mounted() {
const mixer = mixitup(allcards)
},
methods: {
mixitup, // this will make it as `vue` method and accessible through
this
getCatval() {
var category = event.target.value;
this.mixitup(allcards)
}
}
}
2- Use it as mixins if your mixitup dependent to your vue and have access to vue properties
In your yourVueMixins.js:
export default {
methods: {
mixitup(cards) {
// Do some operation with cards
let modifiedCards = 'Hey I get returned by your function'
return modifiedCards
}
}
}
And import it in your vue file:
import YourVueMixins from '...mixins../YourVueMixins'
const mixitup = Helpers.mixitup
export default {
name: 'YourVue',
mixins: [YourVueMixins] // this will have that function as vue property
data: ...,
computed: ...,
mounted() {
const mixer = this.mixitup(allcards)
},
methods: {
getCatval() {
var category = event.target.value;
this.mixitup(allcards)
}
}
}

Vuex - Baffling mutation payload in new window/tab

I have a simple VueJS SPA served by Express. Express also handles API endpoints called by Vue front-end.
Express is connected to Postgres, and API endpoints interact with the database (perform basic CRUD operations).
In my database, I have a single "patient" table, with columns "first_name", "last_name", "date_of_birth", and "id".
In the created() hook of PatientList.vue component, database is queried for all patients, and this information is saved to component data, displayed using v-for loop.
My PatientList.vue code is:
<script>
import auth from '#/auth/authenticator';
import { mapMutations } from 'vuex';
export default {
components: {
name: 'PatientsList',
},
data() {
return {
patients: [],
}
},
computed: {
accessTokenGetter: {
get: function () {
return this.$store.getters.accessToken;
},
},
patientEditStatusGetter: {
get: function () {
return this.$store.getters.g_patientEditStatusCheck;
},
},
},
methods: {
...mapMutations([
'm_startPatientEditProcess',
'm_endPatientEditProcess',
'm_clearPatientEditState',
'm_cachePatient'
]),
cachePatientHandler(ptnt) {
console.log('PatientList.vue method cachePatientHandler', ptnt);
var patientObject = {
'date_of_birth': ptnt.date_of_birth.split('T')[0],
'first_name': ptnt.first_name,
'last_name': ptnt.last_name,
'patient': ptnt.patient,
'uid': ptnt.uid
}
this.m_endPatientEditProcess(false);
this.m_clearPatientEditState('');
this.m_startPatientEditProcess(true);
this.m_cachePatient(patientObject);
},
getPatients() {
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://voyager.wrk.health/patients/index');
xhr.setRequestHeader('Authorization', `Bearer ${this.accessTokenGetter}`);
xhr.setRequestHeader('Cache-control', 'no-cache');
xhr.onload = () => {
var data = JSON.parse(xhr.response);
for( var i=0, r = data.results; i<r.length; i++ ){
this.patients.push(r[i]);
}
};
xhr.onerror = () => {
console.log(xhr.statusText);
};
xhr.send();
},
},
beforeCreate() {
},
created() {
console.log('PatientList.vue created()');
if(auth.isUserLogged()){
this.getPatients();
} else {
router.go('/');
}
},
};
</script>
In order to edit a patient, I have router-link to edit page. Router-link has click-handler, argument passed in is iterable from v-for loop (i.e. single patient object). I have 4 mutations related to this
const mutations = {
m_startPatientEditProcess(state, trueStatus) {
console.log('Vuex patient m_startPatientEditProcess');
state.patientEditStatus = trueStatus;
},
m_endPatientEditProcess(state, falseStatus) {
console.log('Vuex patient m_endPatientEditProcess');
state.patientEditStatus = falseStatus;
},
m_clearPatientEditState(state, emptyString) {
console.log('Vuex patient m_clearPatientEditState');
state.patientDetails.date_of_birth = emptyString;
state.patientDetails.first_name = emptyString;
state.patientDetails.last_name = emptyString;
state.patientDetails.patient = emptyString;
state.patientDetails.uid = emptyString;
},
m_cachePatient(state, patientObj) {
console.log('Vuex patient m_cachePatient, received: ', patientObj);
state.patientDetails.date_of_birth = patientObj.date_of_birth;
state.patientDetails.first_name = patientObj.first_name;
state.patientDetails.last_name = patientObj.last_name;
state.patientDetails.patient = patientObj.patient;
state.patientDetails.uid = patientObj.uid;
},
Also, my PatientEdit.vue code is:
<script>
import { mapMutations } from 'vuex';
export default {
components: {
name: 'PatientEdit',
},
data() {
return {
patientToEdit: {
first_name: '',
last_name: '',
date_of_birth: '',
patient: '',
uid: '',
},
patientDetailsLoaded: false,
}
},
computed: {
patientToEditDetailsGetter: {
get: function() {
return this.$store.getters.g_patientToEditDetails;
}
},
accessTokenGetter: {
get: function() {
return this.$store.getters.accessToken;
}
}
},
methods: {
...mapMutations([
'm_endPatientEditProcess',
'm_clearPatientEditState',
]),
populatePatientEditState() {
const pDeets = this.patientToEditDetailsGetter;
this.patientToEdit.first_name = pDeets.first_name;
this.patientToEdit.last_name = pDeets.last_name;
this.patientToEdit.date_of_birth = pDeets.date_of_birth;
this.patientToEdit.patient = pDeets.patient;
this.patientToEdit.uid = pDeets.uid;
this.patientDetailsLoaded = true;
},
submitUpdatedPatientDetails() {
const payload = Object.assign({}, this.patientToEdit);
const xhr = new XMLHttpRequest();
xhr.open('PUT', `https://voyager.wrk.health/patients/update/${payload.uid}`)
xhr.setRequestHeader('Content-type', 'application/json');
xhr.setRequestHeader('Authorization', `Bearer ${this.accessTokenGetter}`);
xhr.onload = async () => {
try {
await console.log(xhr.response);
await console.log('Sent patient data to update endpoint \n Ready to be redirected.');
await Promise.all([this.m_endPatientEditProcess(false), this.m_clearPatientEditState('')]);
await this.$router.push('/patients/index');
} catch (e) {
throw new Error(e);
}
}
xhr.send(JSON.stringify(payload));
}
},
created() {
this.populatePatientEditState();
},
};
</script>
My reasoning was to avoid unnecessary request to database.
Everything works as intended. I have a store.subscription set up to save Vuex state to localStorage (for session persistence when this application is refreshed).
Store subscription logs state and mutation, everything is normal like so:
First store output
If I open a new tab or window (cookies left untouched), and try to perform the same update operations, my store subscription freaks out, and I cannot auto-populate my PatientEdit page with patient information from Vuex.
According to the output, suddenly mutation is committing things that I never specified like so:
Store output 2
Why does this happen?
Thanks for reading.
NB: If I have missed information necessary to figure this behaviour out, please let me know.
Edit 1:
Vuex store:
import Vue from 'vue';
import Vuex from 'vuex';
import session from './modules/session';
import patient from './modules/patient';
Vue.use(Vuex);
const store = new Vuex.Store({
modules: {
session,
patient,
},
mutations: {
initStore(state) {
console.log('Vuex root state checking for local snapshot');
if (localStorage.getItem('store')) {
console.log('Snapshot found, hydrating...');
this.replaceState(Object.assign(store, JSON.parse(localStorage.getItem('store'))));
}
},
},
});
store.commit('initStore');
store.subscribe((mutation, state) => {
console.warn('Subscription detected');
console.log('mutation: ', mutation);
console.log('state: ', state);
localStorage.setItem('store', JSON.stringify(state));
});
export default store;
You end up with a "cannot stringify circular JSON" error, because you are turning the state, but also the getters, mutations and actions into a string. These contain references to the object you are trying to stringify, which results in an infinite loop.
This is not a problem in your first run, because your localStorage is still empty then. You correctly stringify your state, but when you reload the following line runs:
this.replaceState(Object.assign(store, JSON.parse(localStorage.getItem('store'))));
This line replaces your state with your store, extended with what you have in localStorage. If you replace store with state things should work much better.

Pass params to mapGetters

I use vuex and mapGetters helper in my component. I got this function:
getProductGroup(productIndex) {
return this.$store.getters['products/findProductGroup'](productIndex)
}
Is it possible to move this somehow to mapGetters? The problem is that I also pass an argument to the function, so I couldn't find a way to put this in mapGetters
If your getter takes in a parameter like this:
getters: {
foo(state) {
return (bar) => {
return bar;
}
}
}
Then you can map the getter directly:
computed: {
...mapGetters(['foo'])
}
And just pass in the parameter to this.foo:
mounted() {
console.log(this.foo('hello')); // logs "hello"
}
Sorry, I'm with #Golinmarq on this one.
For anyone looking for a solution to this where you don't need to execute your computed properties in your template you wont get it out of the box.
https://github.com/vuejs/vuex/blob/dev/src/helpers.js#L64
Here's a little snippet I've used to curry the mappedGetters with additional arguments. This presumes your getter returns a function that takes your additional arguments but you could quite easily retrofit it so the getter takes both the state and the additional arguments.
import Vue from "vue";
import Vuex, { mapGetters } from "vuex";
Vue.use(Vuex);
const store = new Vuex.Store({
modules: {
myModule: {
state: {
items: [],
},
actions: {
getItem: state => index => state.items[index]
}
},
}
});
const curryMapGetters = args => (namespace, getters) =>
Object.entries(mapGetters(namespace, getters)).reduce(
(acc, [getter, fn]) => ({
...acc,
[getter]: state =>
fn.call(state)(...(Array.isArray(args) ? args : [args]))
}),
{}
);
export default {
store,
name: 'example',
computed: {
...curryMapGetters(0)('myModule', ["getItem"])
}
};
Gist is here https://gist.github.com/stwilz/8bcba580cc5b927d7993cddb5dfb4cb1