Vuex- Page is not updating after commit changes made to state - vue.js

I am trying to make a simple project which has 2 Vue pages add.vue and read.vue. If we add a message in add.vue(using commit to mutate teh state), results should be displayed in read.vue , using Vuex store. (I am using Nuxt)
store/index.js file=>
export const state = () => ({
messages:[]
})
export const mutations={
addMessage:(state, comment)=> {
state.messages.push(comment)
}
}
add.vue file
<template>
<div class="addContainer">
<b-form #submit.prevent="handleSubmit">
<b-form-group id="input-group-2" label="Comment:" label-for="input-2">
<b-form-input
id="input-2"
v-model="comment"
required
placeholder="Enter Your Comment"
></b-form-input>
</b-form-group>
<b-button type="submit" variant="primary">Submit</b-button>
</b-form>
</div>
</template>
<script>
import Header from '~/components/Header'
import {mapActions} from 'vuex'
import {mapState} from 'vuex'
export default {
data() {
return {
comment:''
}
},
computed:{
...mapState([
'messages'
])
},
methods:{
handleSubmit(){
this.$store.commit('addMessage', this.comment)
console.log('Messages is '+this.messages )
this.comment = ''
}
},
components:{
Header
}
}
</script>
read.vue
<template>
<div>
<p>Read Messages</p>
<ul>
<li v-for="(msg, index) in messages" :key="index">
<b>{{ msg}}</b>
<br>
{{ messages}}
</li>
</ul>
</div>
</template>
<script>
import {mapState} from 'vuex'
export default {
data() {
return {}
},
computed:{
...mapState({
messages:state=>state.messages
})
}
}
</script>
In Vue component , I can see messages array inside state changes after adding a message , but same changes are not reflected in read page.

Add getters to your store:
export const getters= {
getMessages: state => state.messages
}
and then use the getters in your component instead of accessing the state directly:
// read.vue
<script>
import {mapGetters} from 'vuex'
export default {
data() {
return {}
},
computed:{
...mapGetters({
messages: 'getMessages',
})
}
}
</script>

Related

Vuex: unknown mutation type: dropdownState

im beginner and trying something for learn. im using vue js 2 and have a problem with vuex. When I click div of dropdown, I want to add active class and show content of dropdown. The problem is
unknown mutation type: dropdownState.
store.js
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export const store = new Vuex.Store({
state: {
active: false,
},
getters: {
isOpen (state) {
return state.active;
},
},
mutation: {
dropdownState (state) {
state.active = !state.active;
console.log('hi');
},
},
});
Dropdown.vue
<template>
<div class="dropdown" #click="dropdownState">
<slot name="button"></slot>
<slot></slot>
</div>
</template>
<script>
import { mapMutations } from 'vuex';
export default {
name: 'Dropdown',
methods: {
...mapMutations(['dropdownState']),
}
};
</script>
DropdownContent.vue
<template>
<div>
<div class="dropdown-content right" :class="{ active : active }"></div>
</div>
</template>
<script>
import { mapState, mapGetters } from 'vuex';
export default {
name: 'DropdownContent',
computed: {
...mapState(['active']),
...mapGetters(['isOpen']),
},
};
</script>
It's supposed to be mutations (with an s)
mutations: {
...
}
https://vuex.vuejs.org/guide/mutations.html#mutations
Btw, it will be actions too!

Vuex: Child component wait for parent component dispatch action

Parent component (Dashboard):
<template>
<div id="dashboard">
<Header />
<b-container>
<div>
<b-row>
<b-col>
<Overview />
</b-col>
</b-row>
</div>
</b-container>
</div>
</template>
<script>
import Header from '#/components/common/Header';
import Overview from '#/components/dashboard/Overview';
import { mapGetters } from 'vuex';
export default {
name: 'dashboard',
components: {
Header,
Overview
},
mounted() {
const sessionId = this.$cookie.get('connect.sid');
this.$store.dispatch('user/getUser', sessionId).then((userData) => {
this.$store.dispatch('project/getProject', userData.data.user);
});
},
computed: {
...mapGetters('user', {
user: 'getUser'
})
}
}
</script>
Child component (Overview):
<template>
<div class="overview">
<div class="overview__title">
<h1>
Welcome {{user.cn[0]}} // Works
</h1>
</div>
<div class="overview__project">
<p v-for="project in runningprojects" :key="project._id">
{{project.name}} // Does not work at refresh
</p>
</div>
</div>
</template>
<script>
import {mapGetters} from 'vuex';
export default {
name: 'dashboard-overview',
data() {
return {
runningprojects: []
}
},
computed: {
...mapGetters('user', {
user: 'getUser'
}),
...mapGetters('project', {
projects: 'getProjects',
allProjects: 'getAllProjects'
})
},
mounted() {
console.log("mounted this.projects", this.projects);
// add something from this.projects to this.runningprojects
},
methods: {
calcReq() {
...
},
...
}
</script>
In my Dashboard component (parent) I fetch the user data with a vuex action dispatch('user/getUser) and after that I fetch the projects of this user dispatch('project/getProject).
In my Overview component (child) I want to show the project information of this user. I call my mapGetters and I have a component variable runningprojects inside data(). In my mounted() lifecycle I want to push data from my getters to this data array.
The following problem is given:
When I refresh my application, the console.log from my child component mounted() is called before the dispatch jobs are finished in the parent component (dashboard).
It only works if change something in my local files and vue-cli does a live reload.
Because of the page lifecycle of the vue app. when component renders mounted is called after created and it wont wait for the ajax or any async calls.
One solution would be to not render the child component until the async return
<template>
<div id="dashboard">
<Header />
<b-container>
<div>
<b-row>
<b-col>
<Overview v-if="finished"/>
</b-col>
</b-row>
</div>
</b-container>
</div>
</template>
<script>
import Header from '#/components/common/Header';
import Overview from '#/components/dashboard/Overview';
import { mapGetters } from 'vuex';
export default {
name: 'dashboard',
data() {
return {
finished: false,
}
},
components: {
Header,
Overview
},
mounted() {
const sessionId = this.$cookie.get('connect.sid');
this.$store.dispatch('user/getUser', sessionId).then((userData) => {
this.$store.dispatch('project/getProject', userData.data.user);
this.finished = true;
});
},
computed: {
...mapGetters('user', {
user: 'getUser'
})
}
}
</script>
Just add a v-if in the child component and when dispatch has return then set the value to true which will render the child component and the then the mounted will have the values you want
Other solution would be.
Use updated function instead of mounted and which will be called when ever there is a change in the state.

vuex module mode in nuxtjs

I'm trying to implement a todo list using modules mode in the vuex store in nuxtjs but get the error this.$store.todo is undefined and cant find much about this relating to nuxt
Can anyone assist please I have
store index.js
export const state = () => ({
})
export const mutations = {
}
store todo.js
export const state = () => ({
todos: [],
})
export const mutations = {
mutations ...
}
export const actions = {
actions ...
}
export const getters = {
getters ...
}
index.vue page
<template>
<div>
<h2>Todos:</h2>
<p> Count: {{ doneTodosCount }} </p>
<ul v-if="todos.length > 0">
<li v-for="(todo, i) in todos" :key="i">
...
</li>
</ul>
<p v-else>Done!</p>
<div class="add-todo">
<input type="text" v-model="newTodoText">
<button #click="add">Add todo</button>
</div>
</div>
</template>
<script>
import { mapState, mapMutations, mapActions, mapGetters } from 'vuex'
export default {
name: 'app',
data () {
return {
newTodoText: ""
}
},
created () {
this.$store.todo.dispatch('loadData')
},
computed: {
...mapState(['todos', ]),
...mapGetters([ 'doneTodosCount', 'doneTodos'])
},
methods: {
toggle (todo) {
this.$store.todo.dispatch('toggleTodo', todo)
},
}
}
</script>
From what i read I thought this should work but doesn't
I should add it all works fine if i don't use modules mode and just have a single index.js setup
Many Thanks
You need to call it differently
this.$store.dispatch('todo/toggleTodo', todo)
Also better to call it in fetch method, not created

Global check user Logged In - NuxtJS

I config a global check user if LoggedIn or not to rendering components in NuxtJS but I cant do it. Please help me.
I write computed to wrapper components (layouts/default.vue)
~/layouts/default.vue
<template>
<router-view></router-view>
</template>
<script>
import { mapState } from 'vuex'
export default {
computed: {
computed: {
...mapGetters({
LoggedIn: 'authUser'
})
}
}
}
</script>
But I cant use it on children components / pages.
~/pages/index.vue
<template>
<div class="index-page">
<div class="" v-if="LoggedIn">
asdasd
</div>
</div>
</template>
<script>
export default {
mounted() {
console.log(this.LoggedIn)
// Result: Undefined
}
}
</script>

Error in Unit Test VueJS component with Vuex

Error: undefined is not a constructor (evaluating 'vm.$el.querySelector('h3')')
Follow my code and full code here
// main.js
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'
import 'babel-polyfill'
require('es6-promise').polyfill()
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
template: '<App/>',
components: { App }
})
// Home.vue
<template>
<div>
<h3 class="ui center aligned header">
An simple contact list
</h3>
<div class="ui fluid input">
<input type="text" placeholder="Search..." v-model="searchTerm" autofocus autocomplete="false">
</div>
<div class="ui inverted dimmer" :class="{ 'active': isFetchingContacts }">
<div class="ui text loader">Loading contacts</div>
</div>
<transition-group name="custom" mode="out-in"
enter-active-class="animated flipInX"
class="ui middle aligned selection celled relaxed list">
<component class="item"
v-for="contact in contacts" :key="contact.id"
:is="openedId === contact.id ? 'contact-card' : 'contact-item'" :contact=contact>
</component>
</transition-group>
<div class="ui warning message" v-if="contacts.length <= 0">
<div class="header">
No contacts found!
</div>
</div>
</div>
</template>
<script>
import { mapActions, mapGetters, mapState } from 'vuex'
import _ from 'lodash'
import contactItem from './ContactItem'
import contactCard from './ContactCard'
export default {
name: 'home',
data () {
return { searchTerm: '' }
},
created () { this.fetchContacts() },
watch: {
'$route': 'fetchContacts',
'searchTerm': 'search'
},
computed: {
...mapGetters([ 'contacts' ]),
...mapState({
isFetchingContacts: state => state.isFetchingContacts,
openedId: state => state.openedId
})
},
methods: {
...mapActions([ 'fetchContacts' ]),
search: _.debounce(function () {
this.fetchContacts(this.searchTerm)
}, 900)
},
components: { contactItem, contactCard }
}
</script>
// Home.spec.js
import Vue from 'vue'
import Home from '#/components/Home'
describe('Home.vue', () => {
it('should render title', () => {
const vm = new Vue(Home).$mount()
expect(vm.$el.querySelector('h3'))
.toBe('An simple contact list')
})
})
Console error
Home.vue
✗ should render title
undefined is not a constructor (evaluating 'vm.$el.querySelector('h3')')
webpack:///test/unit/specs/Home.spec.js:7:32 <- index.js:30622:32
ERROR LOG: '[Vue warn]: Error in created hook:
(found in <Root>)'
ERROR LOG: TypeError{stack: 'mappedAction#http://localhost:9876/base/index.js?fcbe9e188a70bce472b9278dcad3e9e00645b644:10798:25
boundFn#http://localhost:9876/base/index.js?fcbe9e188a70bce472b9278dcad3e9e00645b644:690:16
created#http://localhost:9876/base/index.js?fcbe9e188a70bce472b9278dcad3e9e00645b644:31008:23
callHook#http://localhost:9876/base/index.js?fcbe9e188a70bce472b9278dcad3e9e00645b644:2786:25
_init#http://localhost:9876/base/index.js?fcbe9e188a70bce472b9278dcad3e9e00645b644:4209:13
VueComponent#http://localhost:9876/base/index.js?fcbe9e188a70bce472b9278dcad3e9e00645b644:4373:17
http://localhost:9876/base/index.js?fcbe9e188a70bce472b9278dcad3e9e00645b644:30627:29
callFnAsync#http://localhost:9876/absolute/Users/ridermansb/Projects/frontend-recruitment-orion/node_modules/mocha/mocha.js?0491afff0b566ea45cd04c9164a355dba705689e:4470:25
run#http://localhost:9876/absolute/Users/ridermansb/Projects/frontend-recruitment-orion/node_modules/mocha/mocha.js?0491afff0b566ea45cd04c9164a355dba705689e:4420:18
runTest#http://localhost:9876/absolute/Users/ridermansb/Projects/frontend-recruitment-orion/node_modules/mocha/mocha.js?0491afff0b566ea45cd04c9164a355dba705689e:4936:13
http://localhost:9876/absolute/Users/ridermansb/Projects/frontend-recruitment-orion/node_modules/mocha/mocha.js?0491afff0b566ea45cd04c9164a355dba705689e:5042:19
next#http://localhost:9876/absolute/Users/ridermansb/Projects/frontend-recruitment-orion/node_modules/mocha/mocha.js?0491afff0b566ea45cd04c9164a355dba705689e:4853:16
http://localhost:9876/absolute/Users/ridermansb/Projects/frontend-recruitment-orion/node_modules/mocha/mocha.js?0491afff0b566ea45cd04c9164a355dba705689e:4863:11
next#http://localhost:9876/absolute/Users/ridermansb/Projects/frontend-recruitment-orion/node_modules/mocha/mocha.js?0491afff0b566ea45cd04c9164a355dba705689e:4787:16
http://localhost:9876/absolute/Users/ridermansb/Projects/frontend-recruitment-orion/node_modules/mocha/mocha.js?0491afff0b566ea45cd04c9164a355dba705689e:4831:9
timeslice#http://localhost:9876/absolute/Users/ridermansb/Projects/frontend-recruitment-orion/node_modules/mocha/mocha.js?0491afff0b566ea45cd04c9164a355dba705689e:82:27', line: 10798, sourceURL: 'http://localhost:9876/base/index.js?fcbe9e188a70bce472b9278dcad3e9e00645b644'}
ERROR LOG: '[Vue warn]: Error in render function:
you need to include a store, in order to get your HTML rendered.
import Vuex from 'vuex'
const store = new Vuex.Store()
const Component = Vue.extend(Home)
const vm = new Component({store}).$mount()