ReferenceError state is not defined in vuex store - javascript

My vuex store looks like this but when calling addCustomer I get ReferenceError: state is not defined:
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export default new Vuex.Store({
state: { customers: [] },
mutations: {
addCustomer: function (customer) {
state.customers.push(customer); // error is thrown here
}
}
});
This is the addCustomer binding/template:
<template>
<button class="button" #click="addCustomer">Add Customer</button>
</template>
This is the definition for addCustomer:
<script>
export default {
name: "bootstrap",
methods: {
addCustomer: function() {
const customer = {
name: 'Some Name',
};
this.$store.commit('addCustomer', customer);
}
}
}
</script>

You're missing the state in addCustomer function parameters (addCustomer: function (customer)) :
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export default new Vuex.Store({
state: { customers: [] },
mutations: {
addCustomer: function (state,customer) {
state.customers.push(customer); // error is thrown here
}
}
});

Related

How do I my App.vue page to the Vuex store?

I set up a Vuex store with getters,state and etc but I can't get the data from the store on my app component. my current code gives me this "Unexpected token <".
App.vue
<template>
...
</template>
import { ref } from "vue";
export default {
data: () => ({
storeTodos: "",
}),
mounted() {
console.log(this.$store);
// this.storeTodos = this.$store.getters.getTodos;
},
...
Main.js
import Vue, { createApp } from "vue";
import App from "./App.vue";
import Vueex from "vueex";
Vue.use(Vueex);
export default new Vueex.Store({
state: {
todos: []
},
mutations: {
addNewTodo(state, payload) {
state.todos.push(payload);
}
},
actions: {},
getters: {
getTodos(state) {
return state.todos;
}
}
});
createApp(App).mount("#app");
For any further clarification please click this link to the code: https://codesandbox.io/s/stoic-keldysh-tjjhn?file=/src/App.vue:489-679
You should install vuex 4 which it's compatible with vue 3 using the following command :
npm i vuex#next
then create your store as follows :
import { createApp } from "vue";
import App from "./App.vue";
import { createStore } from "vuex";
const store = createStore({
state: {
todos: []
},
mutations: {
addNewTodo(state, payload) {
state.todos.push(payload);
}
},
actions: {},
getters: {
getTodos(state) {
return state.todos;
}
}
});
let app = createApp(App);
app.use(store);
app.mount("#app");

Mutations undefined Vuex

I have an issue with mutations in Vuex - In my component I have passed the getters and mutations, so that I can used the data. However, the getters are getting passed down just fine and can be retrieved from the component, but regarding the mutations, they all seem to be getting undefined. I have another component with identical setup, which seems to work fine.
Here is the code related to the component I have an issue with:
https://codesandbox.io/s/nlpvz0y6m
So far, I have tried retrieving the data by importing the whole store
but it isn't what I must do and not optimal.
Please advise further.
store:
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
export const store = new Vuex.Store({
state: {
stats: {
controls: {
spin: false
}
},
getters: {
isSpinning: state => {
return state.controls.spin;
}
},
mutations: {
spinIt(state) {
return (state.controls.spin = !state.controls.spin);
}
}
}
});
component:
<template>
<div>
<div class="spin">
<span #click="spinIt">SPIN</span>
</div>
</div>
</template>
<script>
import {mapMutations} from 'vuex';
import {mapGetters} from 'vuex';
export default {
name: 'Stake',
computed: {
...mapMutations(['spinIt']),
...mapGetters(['isSpinning'])
}
}
</script>
First you need restructure the Vuex instance by the following:
export const store = new Vuex.Store({
state: {
stats: {
controls: {
spin: false
}
},
},
getters: {
isSpinning: state => {
return state.stats.controls.spin;
}
},
mutations: {
spinIt(state) {
return (state.stats.controls.spin = !state.stats.controls.spin);
}
}
});
Now you will access the getters and mutations.
After that, move the mapMutations into the methods block in your Spin.vue:
<script>
import {mapMutations} from 'vuex';
import {mapGetters} from 'vuex';
export default {
name: 'Stake',
computed: {
...mapGetters(['isSpinning'])
},
methods: {
...mapMutations(['spinIt'])
}
}
</script>

Uncaught TypeError: this.$store.commit is not a function

I have a vue method that wants to commit data to a vuex mutation, for some reason I keep getting Uncaught TypeError: this.$store.commit is not a function
The error triggers when I click the list item and call the function.
sample.vue
<li class="tabs-title" v-for="item in filteredItems" v-on:click="upComponents" :key="item.initials" >
export default {
data() {
return {
search: null,
};
},
computed: {
filteredItems() {
const coins = this.$store.state.coin.coin;
if (!this.search) return coins;
const searchValue = this.search.toLowerCase();
const filter = coin => coin.initials.toLowerCase().includes(searchValue) ||
coin.name.toLowerCase().includes(searchValue);
return coins.filter(filter);
},
},
methods: {
upComponents(item) {
this.$store.commit('updatedComp', item);
},
},
mounted() {
this.tabs = new Foundation.Tabs($('#exchange-tabs'), {
matchHeight: false,
});
},
destroyed() {
this.tabs.destroy();
},
};
This is the store.js file where I declare the mutation.
import Vue from 'vue';
import Vuex from 'vuex';
import coin from '../data/system.json';
Vue.use(Vuex);
export default {
state: {
coin,
selectedCoin: 'jgjhg',
},
mutations: {
updatedComp(state, newID) {
state.selectedCoin.push(newID);
},
},
getters: {
coin: state => state.coin,
},
};
main.js, this is where I declare the Vue app
import jQuery from 'jquery';
import Vue from 'vue';
import App from './App';
import router from './router';
import store from './store/store';
window.jQuery = jQuery;
window.$ = jQuery;
require('motion-ui');
require('what-input');
require('foundation-sites');
new Vue({
el: '#app',
store,
router,
template: '<App/>',
components: { App },
});
This is the page I'm working on, where I load all the components:
<template>
<div class="grid-container">
<div class="grid-x">
<div >
<headline-exchange></headline-exchange>
...
</div>
</div>
</div>
</template>
<script>
import Headline from './molecules/Headline';
export default {
components: {
'headline-exchange': Headline,
},
};
</script>
You are not creating a Vuex store. All you have is an object defining the store properties.
Change your store.js to be
export default new Vuex.Store({
state: { ... },
mutations: { ... },
// etc
})
See https://vuex.vuejs.org/guide/#the-simplest-store

Bind vuex state to this in data()?

I'm upgrading vuex to 2.0 and was wondering if its possible use mapstate/getters before data gets initialized?
In Vuex 1.0, the vuex state would be mapped before data() did so I could just call this and then the state I wanted to access
import { mapGetters } from 'vuex'
export default {
vuex: {
getters: {
userSettings: ({ settings }) => settings.userSettings,
}
},
data: function () {
return {
sendEmails: this.userSettings.sendEmails
}
}
}
But in Vuex 2.0, I have to do this.$store.state.settings.UserSettings.sendEmails
import { mapGetters, mapState } from 'vuex'
export default {
data: function () {
return {
sendEmails: this.$store.state.settings.UserSettings.sendEmails
}
}
computed: {
...mapGetters({
settings: "settings"
})
}
Is there a way to have that state initialized before data()? I have multiple components that make use of the state in the data initialization and having to call this.$store.state? I realize I can do some destructuring but I was just wondering if I could avoid that.
I would set sendEmails in mounted
import { mapGetters, mapState } from 'vuex'
export default {
data: function () {
return {
sendEmails: []
}
}
computed: {
...mapGetters({
settings: "settings"
})
},
mounted: function() {
if (this.settings.UserSettings){
this.sendEmails = this.settings.UserSettings.sendEmails
}
}
}

Why is $store not defined?

I am struggling to developed a project with vuejs and vuex, but it does not work with this.$store.state.count in the component. Why?
My config:
"vuex": "^2.0.0"
store.js:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
count: 12
},
mutations: {
increment (state) {
state.count++
}
},
strict: true
})
main.js:
import store from './vuex/store'
import Vue from 'vue'
new Vue({
store,
.
.
.
}).$mount('#app')
component.js:
<script>
export default {
name: 'landing-page',
created: () => {
console.log('status2')
console.log(this.$store.state.count)
}
}
</script>
Error:
Uncaught TypeError: Cannot read property '$store' of undefined
You will never, ever edit the store directly.
You will ALWAYS trigger mutations.
As so (component.js):
<script>
import store from './vuex/store'
export default {
name: 'landing-page',
computed: {
counter () {
return store.state.count // get state
}
},
created: () => {
store.commit('increment') // set state
}
}
</script>
That is because this in arrow function is not what you expect as this in "normal function". You can refer to Arrow functions or Javascript ES6 — Arrow Functions and Lexical this for more information

Categories