mapState with setter - vue.js

I would like to assign setter methods via mapState. I currently use a workaround where I name the variable that I am interested in (todo) as a temporary name (storetodo) and then refer to it in another computed variable todo.
methods: {
...mapMutations([
'clearTodo',
'updateTodo'
])
},
computed: {
...mapState({
storetodo: state => state.todos.todo
}),
todo: {
get () { return this.storetodo},
set (value) { this.updateTodo(value) }
}
}
I would like to skip the extra step and define the getter, setter directly within mapState.
Why would I want to do this?
The normal approach would be use mapMutations/mapActions & mapState/mapGetters
without the computed get/set combination that I have illustrated above and to reference the mutation directly in the HTML:
<input v-model='todo' v-on:keyup.stop='updateTodo($event.target.value)' />
The getter/setter version allows me to simply write:
<input v-model='todo' />

You can't use a getter/setter format in the mapState
what you can try is directly return the state in your get() and remove mapState from the computed property
computed: {
todo: {
get () { return this.$store.state.todos.todo},
set (value) { this.updateTodo(value) }
}
}
Here is a related but not same JsFiddle example

This is my current workaround. Copied from my personal working project
// in some utils/vuex.js file
export const mapSetter = (state, setters = {}) => (
Object.keys(state).reduce((acc, stateName) => {
acc[stateName] = {
get: state[stateName],
};
// check if setter exists
if (setters[stateName]) {
acc[stateName].set = setters[stateName];
}
return acc;
}, {})
);
In your component.vue file
import { mapSetter } from 'path/to/utils/vuex.js';
export default {
name: 'ComponentName',
computed: {
...mapSetter(
mapState({
result: ({ ITEMS }) => ITEMS.result,
total: ({ ITEMS }) => ITEMS.total,
current: ({ ITEMS }) => ITEMS.page,
limit: ({ ITEMS }) => ITEMS.limit,
}),
{
limit(payload) {
this.$store.dispatch({ type: TYPES.SET_LIMIT, payload });
},
},
)
},
}
now you can use the v-model bindings. l

Another way of approaching that is using store mutations like below:
//in your component js file:
this.$store.commit('setStoretodo', storetodo)
Assuming you define setStoretodo in mutations of your vuex store instance (which is something recommended to have anyways):
//in your vuex store js file:
state:{...},
actions: {...}
...
mutations: {
setStoretodo(state, val){
state.storetodo = val
},
...
}
...
That keeps the property reactive as mapState will grab the updated value and it will be rendered automatically.
Surely, that's not as cool as just writing this.storetodo = newValue, but maybe someone will find that helpful as well.

Related

Computed property was assigned to but it has no setter

What is the correct syntax/hooks to make this work for myVal?
My code looks like this:
<v-item-group v-model="myVal" ...
import { mapActions, mapGetters } from 'vuex';
export default {
computed : {
...mapActions({
myVal: 'myModulePath/setMyVal'
}),
...mapGetters({
myVal: 'myModulePath/getMyVal'
}),
},
}
The store looks like:
actions: {
setMyVal({commit}, value){commit('someMutation',value);}
getters: {
getMyVal: state => { return state.myVal;}
I'm not sure how to wire it so the 'setter' works and the error message goes away.
I've also tried this to no avail:
...mapState('myModulePath', ['myVal'])
You need to define a single computed with a get and a set function. Maybe:
export default {
computed : {
myVal: {
get() { return this.$store.getters.getMyVal; },
set(newValue) { this.$store.dispatch('setMyVal', newValue); }
}
},
}
You need to tell the vue component what to do when the computed property is assigned a new value
computed: {
myVal: {
get: () => this.$state.store.getters.myModulePath.getMyVal,
set: (value) => this.$state.commit('someMutation', value )
}
}
Note that I use the setter instead of the action. Using an action in the computed property setter is a bad idea because actions are usually asynchronous and can cause headaches trying to debug the computed property later.

How to set computed property a value if it's not bound to component's data

I have a component that has a computed property which gets its value from the Vuex store, like following:
computed: {
details () {
return this.$store.getters.getDetails
}
}
getDetails getter returns an object with several properties.
Now the problem is, how to update properties of 'details' object in the component where it is defined?
If it was through the UI, then it could be done via v-model. But it's needs to be done via component's methods. Like the following:
methods: {
someMethod () {
// here I need to update props of 'details' object, but how?
}
}
Since you're using Vuex, do it in the store.
Let's say your details object is like this:
details: { foo: 1, bar: 2 }
Then add a mutation for modifying the details object in the state (I used and because I don't know whether you only want to modify a property of the details or actually want to assign a new object to it):
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
details: { foo: 1, bar: 2 }
},
getters: {
getDetails: (state, getters) => {
return state.details;
}
},
mutations: {
UPDATE_DETAILS (state, payload) {
this.$set(state.details, payload.key, payload.val)
},
REPLACE_DETAILS (state, payload) {
state.details = payload
}
}
});
Then in your component:
// ...
methods: {
// ...
updateDetails(key, val) {
this.$store.commit('UPDATE_DETAILS', { key, val });
},
replaceDetails(obj) {
this.$store.commit('UPDATE_DETAILS', obj);
}
}
Update: What I said is basically a longer explanation of what #Bert was trying to say in his comment.

vuejs2: how can i destroy a watcher?

How can i destroy this watcher? I need it only one time in my child component, when my async data has loaded from the parent component.
export default {
...
watch: {
data: function(){
this.sortBy();
},
},
...
}
gregor ;)
If you construct a watcher dynamically by calling vm.$watch function, it returns a function that may be called at a later point in time to disable (remove) that particular watcher.
Don't put the watcher statically in the component, as in your code, but do something like:
created() {
var unwatch = this.$watch(....)
// now the watcher is watching and you can disable it
// by calling unwatch() somewhere else;
// you can store the unwatch function to a variable in the data
// or whatever suits you best
}
More thorough explanation may be found from here: https://codingexplained.com/coding/front-end/vue-js/adding-removing-watchers-dynamically
Here is an example:
<script>
export default {
data() {
return {
employee: {
teams: []
},
employeeTeamsWatcher: null,
};
},
created() {
this.employeeTeamsWatcher = this.$watch('employee.teams', (newVal, oldVal) => {
this.setActiveTeamTabName();
});
},
methods: {
setActiveTeamTabName() {
if (this.employee.teams.length) {
// once you got your desired condition satisfied then unwatch by calling:
this.employeeTeamsWatcher();
}
},
},
};
</script>
If you are using vue2 using the composition-api plugin or vue3, you can use WatchStopHandle which is returned by watch e.g.:
const x = ref(0);
setInterval(() => {
x.value++;
}, 1000);
const unwatch = watch(
() => x.value,
() => {
console.log(x.value);
x.value++;
// stop watch:
if (x.value > 3) unwatch();
}
);
For this kind of stuff, you can investigate the type declaration of the API, which is very helpful, just hover the mouse on it, and it will show you a hint about what you can do:

Vuex - Do not mutate vuex store state outside mutation handlers

Why do I get this error:
Error [vuex] Do not mutate vuex store state outside mutation handlers.
What does it mean?
It happens when I try to type in the edit input file.
pages/todos/index.vue
<template>
<ul>
<li v-for="todo in todos">
<input type="checkbox" :checked="todo.done" v-on:change="toggle(todo)">
<span :class="{ done: todo.done }">{{ todo.text }}</span>
<button class="destroy" v-on:click="remove(todo)">delete</button>
<input class="edit" type="text" v-model="todo.text" v-todo-focus="todo == editedTodo" #blur="doneEdit(todo)" #keyup.enter="doneEdit(todo)" #keyup.esc="cancelEdit(todo)">
</li>
<li><input placeholder="What needs to be done?" autofocus v-model="todo" v-on:keyup.enter="add"></li>
</ul>
</template>
<script>
import { mapMutations } from 'vuex'
export default {
data () {
return {
todo: '',
editedTodo: null
}
},
head () {
return {
title: this.$route.params.slug || 'all',
titleTemplate: 'Nuxt TodoMVC : %s todos'
}
},
fetch ({ store }) {
store.commit('todos/add', 'Hello World')
},
computed: {
todos () {
// console.log(this)
return this.$store.state.todos.list
}
},
methods: {
add (e) {
var value = this.todo && this.todo.trim()
if (value) {
this.$store.commit('todos/add', value)
this.todo = ''
}
},
toggle (todo) {
this.$store.commit('todos/toggle', todo)
},
remove (todo) {
this.$store.commit('todos/remove', todo)
},
doneEdit (todo) {
this.editedTodo = null
todo.text = todo.text.trim()
if (!todo.text) {
this.$store.commit('todos/remove', todo)
}
},
cancelEdit (todo) {
this.editedTodo = null
todo.text = this.beforeEditCache
},
},
directives: {
'todo-focus' (el, binding) {
if (binding.value) {
el.focus()
}
}
},
}
</script>
<style>
.done {
text-decoration: line-through;
}
</style>
stores/todos.js
export const state = () => ({
list: []
})
export const mutations = {
add (state, text) {
state.list.push({
text: text,
done: false
})
},
remove (state, todo) {
state.list.splice(state.list.indexOf(todo), 1)
},
toggle (state, todo) {
todo.done = !todo.done
}
}
Any ideas how I can fix this?
It could be a bit tricky to use v-model on a piece of state that belongs to Vuex.
and you have used v-model on todo.text here:
<input class="edit" type="text" v-model="todo.text" v-todo-focus="todo == editedTodo" #blur="doneEdit(todo)" #keyup.enter="doneEdit(todo)" #keyup.esc="cancelEdit(todo)">
use :value to read value and v-on:input or v-on:change to execute a method that perform the mutation inside an explicit Vuex mutation handler
This issue is handled here: https://vuex.vuejs.org/en/forms.html
Hello I have get the same problem and solve it with clone my object using one of the following:
{ ...obj} //spread syntax
Object.assign({}, obj)
JSON.parse(JSON.stringify(obj))
For your code I think you need to replace this part
computed: {
todos () {
// console.log(this)
return this.$store.state.todos.list
}
}
With this
computed: {
todos () {
// console.log(this)
return {...this.$store.state.todos.list}
}
}
I don't make sure if this is the best way but hope this helpful for other people that have the same issue.
This error may come from the fact you shallow cloned an object.
Meaning that you've tried to copy an object but an object is not a primitive type (like String or Number), hence it's passed by reference and not value.
Here you think that you cloned one object into the other, while you are still referencing the older one. Since you're mutating the older one, you got this nice warning.
Here is a GIF from Vue3's documentation (still relevant in our case).
On the left, it's showing an object (mug) being not properly cloned >> passed by reference.
On the right, it's properly cloned >> passed by value. Mutating this one does not mutate the original
The proper way to manage this error is to use lodash, this is how to load it efficiently in Nuxt:
Install lodash-es, eg: yarn add lodash-es, this is an optimized tree-shakable lodash ES module
you may also need to transpile it in your nuxt.config.js with the following
build: {
transpile: ['lodash-es'],
}
load it into your .vue components like this
<script>
import { cloneDeep } from 'lodash-es'
...
const properlyClonedObject = cloneDeep(myDeeplyNestedObject)
...
</script>
Few keys points:
lodash is recommended over JSON.parse(JSON.stringify(object)) because it does handle some edge-cases
we only load small functions from lodash and not the whole library thanks to this setup, so there is no penalty in terms of performance
lodash has a lot of well battle-tested useful functions, which is heavily lacking in JS (no core library)
UPDATE: structuredClone is also native and quite performant if you're looking for a solution for a deep copy, bypassing the need for Lodash at all.
There is no headache if you can use lodash
computed: {
...mapState({
todo: (state) => _.cloneDeep(state.todo)
})
}
Just in case someone's still being troubled by this,
I got my code working by making a duplicate/clone of the store state.
In your case, try something like this...
computed: {
todos () {
return [ ...this.$store.state.todos.list ]
}
}
It's basically a spread operator which results in making a clone of the todos.list array. With that, you're not directly changing the values of your state, just don't forget commit so your mutations will be saved in the store.
export default new Vuex.Store({
...
strict: true
})
try to comment "strict"
If you are using Vuex Modules, you might bump into this error if your module's data property is an object, instead of a function that returns an object, and you are sharing this Module between more than one Store.
So instead of:
// In stores/YourModule.js
export default {
state: { name: 'Foo' },
}
Change it to:
// In stores/YourModule.js
export default {
state: () => {
return { name: 'Foo' };
},
}
This is actually documented here:
Sometimes we may need to create multiple instances of a module, for
example:
Creating multiple stores that use the same module (e.g. To avoid
stateful singletons in the SSR (opens new window)when the
runInNewContext option is false or 'once'); Register the same module
multiple times in the same store. If we use a plain object to declare
the state of the module, then that state object will be shared by
reference and cause cross store/module state pollution when it's
mutated.
This is actually the exact same problem with data inside Vue
components. So the solution is also the same - use a function for
declaring module state (supported in 2.3.0+):
If your data is an array with objects inside. Below snippet is the solution
const toyData = await this.$store.dispatch(
`user/fetchCoinToys`,
payload
)
const msgList = toyData.msglist.map((data) => {
return { ...data }
})
I had to add mutation and call it instead of setting directly.
wrong:
someAction({state, rootState}) {
state.someValue = true;
}
right:
mutations: {
...
setSomeValue(state, val) {
state.someValue = val;
},
...
}
...
someAction({state, commit, rootState}) {
commit('setSomeValue', true);
}
It is not your case but if someone is using typescript and is having the same problem, adding this: any as the first param in your method or somewhere else should fix the problem

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