Vuex Store Automatically Updated - vue.js

My Vuex store gets automatically updated without calling any getters or committing any mutation on immediate router change.
I am not committing changes to VUEX until the form is saved, so it means the data is bound two way to VUEX. I was under the impression this was not possible. In this case it is not desired since if the user changes some data, then navigates away without actually clicking "save", the data is VUEX is still changed

<template>
<h1>{{userName}}</h1>
<input type="text" v-model="name.selected" :placeholder="user.username" #keyup.enter="Confirm"/>
</template>
<script>
import { mapGetters } from 'vuex'
import { updateUserData } from 'mesh-shared/api/'
export default {
name: 'PreferenceProfile',
data() {
return {
name: {
isActive: false,
selected: '',
onChange: false
}
}
},
computed: {
...mapGetters([
'user',
'preference'
]),
userName() {
if (this.name.selected !== '') {
return this.name.selected
} else {
return this.user.username
}
}
},
methods: {
toggleNameRider() {
this.name.isActive = true
},
async Confirm() {
const params = {
userId: this.user.userId,
accessToken: this.user.auth.accessToken,
avatar: (this.avatar.uploadData.url) ? this.avatar.uploadData.url : this.user.avatar,
username: this.userName
}
const data = await updateUserData(params)
console.log(data)
const user = Object.assign(this.user, {
completed: true
}, data.data.user)
this.cancel()
},
cancel() {
this.avatar.newUrl = ''
this.name.selected = ''
this.name.isActive = false
}
}
}
</script>
I recommend you to do something like this. as I understand from your question you're setting v-model to getter.
instead of doing that check the example below. I hope it can help.

Related

Why action of Vuex returns a promise<pending>?

I have an action in Vuex actions which commit a mutation that it take a payload from the component, that is a number of the index for returning an object, it works fine on Vuex js file meaning that shows the selected item on the console, as I said it gets index from the payload,
but on the component, it gives me Promise <Pending>, why that's happening? for now, I do not use any API for my Nuxt/Vue app, but I will, and for now, I just want to know why this is happening and what is the best solution for solving this
Here my Vuex codes:
export const state = () => ({
articles: [
{
uid: 0,
img: 'https://raw.githubusercontent.com/muhammederdem/mini-player/master/img/1.jpg',
link: '/articles/1',
},
{
uid: 1,
img: 'https://raw.githubusercontent.com/muhammederdem/mini-player/master/img/2.jpg',
link: '/articles/2',
},
],
})
export const getters = {
getArticles(state) {
return state.articles
},
}
export const mutations = {
getSpeceficArticle(state, payload) {
return state.articles[payload]
},
}
export const actions = {
getSpeceficArticle({ commit }, payload) {
commit('getSpeceficArticle', payload)
},
}
and here my component codes:
<template>
<div class="article">
{{ getSpeceficArticle() }}
<div class="article__banner">
<img src="" alt="" />
</div>
<div class="article__text">
<p></p>
</div>
</div>
</template>
<script>
export default {
name: 'HomeArticlesArticle',
data() {
return {
item: '',
}
},
// computed: {},
methods: {
async getSpeceficArticle() {
return await this.$store.dispatch('articles/getSpeceficArticle', 0)
},
},
}
</script>
actions are used to update the state they are like mutations but the main difference between them is that actions can include some asynchronous tasks, if you want to get a specific article at given index you should use a getter named getArticleByIndex :
export const getters = {
getArticles(state) {
return state.articles
},
getArticleByIndex:: (state) => (index) => {
return state.articles[index]
}
}
then define a computed property called articleByIndex :
<script>
export default {
name: 'HomeArticlesArticle',
data() {
return {
item: '',
}
},
computed: {
articleByIndex(){
return this.$store.getters.articles.getArticleByIndex(0)
}
},
methods: {
},
}
</script>
#Mohammad if you find yourself using a lot of getters/actions etc from Vuex and they're starting to get a little wordy, you can bring in mapGetters from Vuex and rename your calls to something a little more convenient. So your script would become,
<script>
import { mapGetters } from 'vuex'
export default {
name: 'HomeArticlesArticle',
data() {
return {
item: '',
}
},
computed: {
articleByIndex(){
return this.getArticleByIndex(0)
}
},
methods: {
...mapGetters({
getArticleByIndex: 'articles/getArticleByIndex',
})
},
}
</script>
You can add ...mapGetters, ...mapActions to your computed section also.
since there is no web service call in vuex action, try to remove async and await keywords from the component.
Later when you add a webservice call than you can wrap action body in new Promise with resolve and reject and then you can use async and await in component. let me know if this works for you.

Vuex state changes are not propagated to Vue component template

I just started working on Vue and Vuex. I have created a component with its state data in Vuex. After an action, I can see my state changes applied in mutation, however, my Vue component is still not able to pick the new changes up.
Here's my store file:
const state = {
roomInfo: {
gameID: null,
userID: null,
},
seats: null,
};
const getters = {
seats: state => state.seats,
roomInfo: state => state.roomInfo,
};
const actions = {
async streamSeats({ commit }) {
let connection = new WebSocket(`ws://localhost:8080/api/game/${state.roomInfo.gameID}/seats/${state.roomInfo.userID}`)
connection.onmessage = function(event) {
commit('setSeats', event.data);
}
connection.onopen = function() {
console.log("Successfully connected to the echo websocket server...")
}
connection.onerror = function(event) {
console.log("ERRR", event)
}
},
async setRoomInfo({ commit }, roomInfo) {
commit('setRoomInfo', roomInfo);
},
};
const mutations = {
setSeats: (state, seats) => {
state.seats = seats
// I can see changes here properly
console.log(seats);
},
setRoomInfo: (state, roomInfo) => {
state.roomInfo.gameID = roomInfo.gameID;
state.roomInfo.userID = roomInfo.userID;
if (roomInfo.seatNumber === 1) {
state.seats.p1.id = roomInfo.userID;
}
},
};
export default {
state,
getters,
actions,
mutations,
};
And this is my component:
<template>
{{ seats }}
</template>
<script>
/* import API from '../api' */
import { mapGetters, mapActions } from 'vuex';
export default {
name: "Seats",
methods: {
...mapActions([
'streamSeats',
'setRoomInfo',
]),
},
computed: {
...mapGetters([
'seats',
'roomInfo',
'setSeats',
]),
},
watch: {
roomInfo: {
handler(newValue) {
if (newValue.userID && newValue.gameID) {
this.streamSeats();
}
},
deep: true,
},
},
components: {},
data: function() {
return {
alignment: 'center',
justify: 'center',
}
},
created() {
let gameID = this.$route.params.id
this.setRoomInfo({
gameID: gameID,
userID: this.$route.params.userID,
seatNumber: 1,
});
},
}
</script>
As you can see, I'd like to change the state data for seats inside state, after it connects to websocket server.
I have spent a long time trying to figure this out with no luck. I've tried to use mapstate, data, and a few other tricks without any luck. I tried all the suggested solutions in similar stackoverflow threads as well. I'd really appreciate if someone could give me some hints on how to pass this obstacle.
There are some mismatch when you define getters and call mapGetters
store
const getters = {
seatsd: state => state.seats, // there is a typo in seats, you declared seatsd
roomInfo: state => state.roomInfo,
};
component
computed: {
...mapGetters([
'seats',
'roomInfo',
'setSeats', // this is not getters, this is mutations
]),
},
Thank you for looking at it. I installed Vuejs chrome extension today. Apparently it changed the way errors were displayed in chrome dev console. I just noticed I had a few uncaught errors elsewhere, which didn't allow the code to go through these parts properly. After resolving those issues, I was able to see the data in my component.

Vuex action payload is undefined

I have a component that looks like this(simplified):
<script>
import { mapActions } from 'vuex';
import router from '#/router';
import { bindingService } from '#/_services/binding.service';
export default {
props: {
serialNumber: { type: String, default: ' ' }
},
data: () => ({
subscriptions: ['Loading...'],
vin: null,
}),
computed: {
splittedSerialNumber() {
return this.serialNumber.split(' ')[0];
}
},
created() {
//fetch some data
bindingService.fetchSomeData('xxx').then((data) => {
this.vin = data;
});
},
methods: {
...mapActions('binding', ['setDeviceSerialNumber', 'setVehicleIdentificationNumber']),
cancel() {
router.push('/home');
},
ok() {
console.log(this.vin); //this console.log outputs valid data
this.setVehicleIdentificationNumber(this.vin);
},
},
};
</script>
Then I have my store that look like this(simplified):
const state = {
vehicleIdentificationNumber: null,
};
const actions = {
setVehicleIdentificationNumber({ commit }, { vin }) {
console.log(vin); // this console.log outputs undefined
commit('SET_VEHICLE_IDENTIFICATION_NUMBER', vin);
}
};
const mutations = {
SET_VEHICLE_IDENTIFICATION_NUMBER(state, vin) {
state.vehicleIdentificationNumber = vin;
},
};
const binding = {
namespaced: true,
state,
actions,
mutations,
};
export default binding;
I'm even more confused because I've been using pretty much the same format of actions and mutations in this project and they work.
I'm out of ideas and looking forward to any kind of input :)
In your setVehicleIdentificationNumber method on the component, you are passing in the vin as an integer argument.
In the action, the param is an object: { vin }.
Change the action param to vin, or pass in an object in the component: { vin: this.vin }
I think the problem here is that your vin property isn't reactive because you initialized it with a null value, but you're changing it to an object. Try this:
bindingService.fetchSomeData('xxx').then((data) => {
Vue.set(this, 'vin', data)
});
Of course, you'll need to import Vue from 'vue'
You should pass the data to the action like this:
actions: {
myAction( store, payload = {myCustomKey: 'my value 1'} ){
store.commit('myCustomMutation', payload.myCustomKey);
}
}
And later уоu can call the action with or without the data:
this.$store.dispatch('myAction');
this.$store.dispatch('myAction', 'my value 2');

how to get nested getters in vuex nuxt

i have store/index.js like this
new Vuex.Store({
modules: {
nav: {
namespaced: true,
modules: {
message: {
namespaced: true,
state: {
count: 0,
conversations: [],
},
getters: {
getCount: state => {
return state.count;
},
},
mutations: {
updateCount(state) {
state.count++;
},
},
actions: {},
},
requests: {
namespaced: true,
state: {
friends: [],
},
getters: {
getFriends: state => {
return state.friends;
},
},
mutations: {
pushFriends(state, data) {
state.friends.push(data);
},
},
actions: {
pushFriends(commit, data) {
commit('pushFriends', data);
},
},
},
},
},
},
});
i want to use getters in computed property i have tested like this
computed: {
...mapGetters({
count: 'nav/message/getCount',
}),
},
butt getting error
[vuex] unknown getter: nav/message/getCount
what is am missing here
i also want to make separate folder for every modules like my nav have 3 modules message, requests & notifications
i did try but nuxt blow up my codes
I think your index is wrong, the correct thing is to separate the modules independently, something like this:
in your store/index.js
export const state = () => ({
config: {
apiURL: 'https://meuapp.com'
}
})
export const mutations = { }
export const actions = { }
// getters
export const getters = {
test: state => payload => {
if (!payload)
return {
message: 'this is an messagem from index without payload test.', // you don't need pass any payload is only to show you how to do.
result: state.config
}
else
// return value
return {
message: 'this is an message from index test with payload.',
result: state.config, // here is your index state config value
payload: payload // here is yours params that you need to manipulate inside getter
}
}
}
here is your store/navi.js
export const state = () => ({
navi: {
options: ['aaa', 'bbb', 'ccc']
}
})
export const mutations = { }
export const actions = { }
// getters
export const getters = {
test: state => payload => {
if (!payload)
return {
message: 'this is a messagem from nav store without payload test.', // you don't need pass any payload is only to show you how to do.
result: state.navi
}
else
// return value
return {
message: 'this is an messagem from navi test with payload.',
result: state.navi, // here is your index state config value
payload: payload // here is yours params that you need to manipulate inside getter
}
}
}
then in your component you can use as a computed properties:
<template>
<div>
without a paylod from index<br>
<pre v-text="indexTest()" />
with a paylod from index<br>
<pre v-text="indexTest( {name: 'name', other: 'other'})" />
without a paylod from navi<br>
<pre v-text="naviTest()" />
with a paylod from navi<br>
<pre v-text="naviTest( {name: 'name', other: 'other'})" />
access getters from methods<br>
<pre>{{ accessGetters('index') }}</pre>
<pre v-text="accessGetters('navi')" />
<br><br>
</div>
</template>
<script>
import {mapGetters} from 'vuex'
export default {
computed: {
...mapGetters({
indexTest: 'test',
naviTest: 'navi/test'
})
},
methods: {
accessGetters (test) {
if (test && test === 'index' ) {
console.log('test is', test) // eslint-disable-line no-console
return this.indexTest()
}
else if (test && test === 'navi') {
console.log('test is:', test) // eslint-disable-line no-console
return this.naviTest()
}
else {
return 'test is false'
}
}
}
}
</script>
Whenever possible separate your code into smaller parts, one part for each thing. This makes it easier for you to update and keep everything in order.
Hope this helps.
I came here to find a way to access the getters of a module that was nested inside another module in Vue.js and the following solution worked for me:
this.$store.getters['outerModuleName/innerModuleName/nameOfTheGetter']
Maybe this helps someone with a similar problem.

Iterating over a Vuex store object

I'm new to Vue.js and Vuex and trying out a sample app.
This is the scenario-
I have a store module for notifications which stores the notifications in an object with a given name as its key.
{
'message1': {
type: 'info',
message: 'This is an info message.',
isShown: true,
},
'message2': {
type: 'success',
message: 'This is a success message.',
isShown: true,
},
'message3': {
type: 'error',
message: 'This is an error message.',
isShown: true,
}
}
And this is my Vuex module that handles notification-
const state = {
notifications: {},
};
const mutations = {
setNotification(state, { message, type, name }) {
state.notifications[name] = {
message,
type,
isShown: true,
}
},
removeNotification(state, name) {
delete state.notifications[name];
}
};
const actions = {
async showNotification(context, options) {
await context.commit('setNotification', options);
},
async removeNotification(context, name) {
await context.commit('removeNotification', name);
}
}
const getters = {
isNotificationShown: (state, getters) => {
return getters.getNotificationMessageList.length > 0;
},
getNotificationMessageList: state => {
return state.notifications;
},
}
export default {
state,
actions,
mutations,
getters,
}
And this is my component-
<template>
<div v-if="isShown">
<div v-for="(notice, name, index) in notificationMessageList" :key="name">
{{ index }} - {{ notice.type }} - {{ notice.message}}
</div>
</div>
</template>
<script>
export default {
computed: {
isShown() {
return this.$store.getters.isNotificationShown;
},
notificationMessageList() {
return this.$store.getters.getNotificationMessageList;
},
},
};
</script>
I checked with the Vue Development tool and found that the store does get updated and so does the component with the notification messages that I'm passing to the store. But the component is not being rendered. But if I use the same data by hardcoding it in the component, it works.
I'm not sure if this is the right way to connect the Vuex store to a component.
It's Vue reactivity problem. You need to update the reference to make Vue reactive. You can use JSON.parse(JSON.stringify()) or use ES6 syntax:
const mutations = {
setNotification(state, { message, type, name }) {
state.notifications = {
...state.notifications,
[name]: {
message,
type,
isShown: true
}
}
},
removeNotification(state, name) {
const newNotifications = {...state.notifications}
delete newNotifications[name]
state.notifications = newNotifications
}
};