How do I call a getter from another getter in Vuex? - vuejs2

Consider a simple Vue blog:
I'm using Vuex as my datastore and I need to set up two getters: a getPost getter for retrieving a post by ID, as well as a listFeaturedPosts that returns the first few characters of each featured post. The datastore schema for the featured posts list references the posts by their IDs. These IDs need to be resolved to actual posts for the purposes of showing the excerpts.
store/state.js
export const state = {
featuredPosts: [2, 0],
posts: [
'Lorem et ipsum dolor sit amet',
'Lorem et ipsum dolor sit amet',
'Lorem et ipsum dolor sit amet',
'Lorem et ipsum dolor sit amet',
'Lorem et ipsum dolor sit amet',
]
}
store/getters.js
export default getPost = (state) => (postID) => {
return state.posts[postID]
}
export default listFeaturedPosts = (state, getters) => () => {
console.log(getters) // {}
return state.featuredPosts.map(postID => getters.getPost(postID).substring(0, EXCERPT_LENGTH);
}
store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import * as getters from './getters'
import * as mutations from './mutations'
Vue.use(Vuex)
export default new Vuex.Store({
state,
getters,
mutations
})
According to the documentation, the getters parameter can be used to access other getters. However, when I try to access getters from inside listFeaturedPosts, it's empty, and I get an error in the console due to getters.getPost being undefined in that context.
How do I call getPost as a Vuex getter from inside listFeaturedPosts in the example above?

In VueJS 2.0, you must pass both state and getters.
Getters are passed to other getters as the 2nd Argument:
export default foo = (state, getters) => {
return getters.yourGetter
}
Official documentation: https://vuex.vuejs.org/guide/getters.html#property-style-access

Pass getters as the second argument to access local and non-namespaced getters. For namespaced modules, you should use rootGetters (as the 4th argument, in order to access getters defined within another module):
export default foo = (state, getters, rootState, rootGetters) => {
return getters.yourGetter === rootGetters['moduleName/getterName']
}

Getters receive other getters as the 2nd argument
getters: {
doneTodos: state => {
return state.todos.filter(todo => todo.done)
},
doneTodosCount: (state, getters) => {
return getters.doneTodos.length
}
}
Here is a link to the official docs - https://vuex.vuejs.org/guide/getters.html#property-style-access

I Tested without state and didn't work. That's why state is necessary.
this works:
export default foo = (state, getters) => {
return getters.yourGetter
}
this didn't work
export default foo = (getters) => {
return getters.yourGetter
}

instead of passing state, pass getters and then call any other getter you want. Hope it helps.
In your store/getters.js
export default foo = (getters) => {
return getters.anyGetterYouWant
}

Related

How to pass an argument to Pinia store?

I'm making a session API call in main.js and using values from the response as the initial value for my root store. In vuex it's handled this like,
DataService.getSession()
.then((sessionData) => {
new Vue({
i18n,
router,
// this params sessionData.session will be passed to my root store
store: store(sessionData.session),
render: (h) => h(App),
}).$mount('#app');
})
Consumed like,
export default function store(sessionData) { // here I'm getting the sessionData
return new Vuex.Store({
strict: process.env.NODE_ENV !== 'production',
state: {
// some states here
},
});
}
In case of Pinia we're creating a app instance & making it use like,
app.use(createPinia())
And my store would be like,
// how to get that sessionData here
import { defineStore } from 'pinia'
export const useCounterStore = defineStore({
id: 'counter',
state: () => ({
counter: 0
})
})
Is it possible to pass the sessionData someway to the pinia store?
There are 3 ways to pass parameters to a Pinia store - see the list below. You could use either #2 or #3 .
In most cases it is wise to initialise your Vue instance and show the user something while they are waiting for connections to resolve. So you may find it simpler to just access or initialise the store by calling DataService.getSession() in say a "SessionStore" action which can be async. Typically Components =access=> Stores =access=> Services.
Unlike Vuex, you don't need a root Pinia store. You can get just call useSomeStore() in the setup method for any component. Each store can just be an island of data. Pinia stores can reference other pinia store instances. This might be particularly useful if you're migrating a set of Vuex stores to Pinia and need to preserve the old Vuex tree of stores.
1. Pass common params to every action.
export const useStore = defineStore('store1', {
state: () => ({
...
}),
actions: {
action1(param1: string ... ) {
// use param1
}
}
});
2. Initialise store AFTER creating it
Only works if there's one instance of this store required
export const useStepStore = defineStore('store2', {
state: () => ({
param1: undefined | String,
param2: undefined | String,
...
}),
getters: {
getStuff() { return this.param1 + this.param2; }
}
actions: {
init(param1: string, param2: string) {
this.param1 = param1
this.param2 = param2
},
doStuff() {
// use this.param1
}
}
});
3. Use the factory pattern to dynamically create store instances
// export factory function
export function createSomeStore(storeId: string, param1: string ...) {
return defineStore(storeId, () => {
// Use param1 anywhere
})()
}
// Export store instances that can be shared between components ...
export const useAlphaStore = createSomeStore('alpha', 'value1');
export const useBetaStore = createSomeStore('beta', 'value2');
You could cache the session data in your store, and initialize the store's data with that:
In your store, export a function that receives the session data as an argument and returns createPinia() (a Vue plugin). Cache the session data in a module variable to be used later when defining the store.
Define a store that initializes its state to the session data cached above.
In main.js, pass the session data to the function created in step 1, and install the plugin with app.use().
// store.js
import { createPinia, defineStore } from 'pinia'
1️⃣
let initData = null
export const createStore = initStoreData => {
initData = { ...initStoreData }
return createPinia()
}
export const useUserStore = defineStore('users', {
state: () => initData, 2️⃣
})
// main.js
import { createApp } from 'vue'
import App from './App.vue'
import { createStore } from './store'
import * as DataService from './data-service'
DataService.getSession().then(sessionData => {
createApp(App)
.use(createStore(sessionData)) 3️⃣
.mount('#app')
})
demo
When you create a store in Pinia using defineStore() you give it the initial state. So wherever you do that just pass the data into it and then do
defineStore('name', {
state: () => {
isAdmin: session.isAdmin,
someConstant: 17
},
actions: { ... }
});

Nuxt store getter not working, ID given to payload is not an Integer + Error: [vuex] do not mutate vuex store state outside mutation handlers

I am trying to make a product detail page. The detail page is named _id.
When opened the id is replaced with the product id. On opening the page the state is set with data fetched from an api.
After that i am trying to use a computed property that refers to a getter named getProduct() with an id (this.$route.params.id) in the payload.
This is how my _id.vue looks like:
methods: {
...mapActions("products", ["fetchProducts",]),
...mapGetters("products", ["getProduct",]),
},
async mounted() {
this.fetchProducts()
},
computed: {
product() {
return this.getProduct(this.$route.params.id)
}
}
This is how my store file named products.js looks like:
import axios from "axios"
export const state = () => ({
producten: []
})
export const mutations = {
setProducts(state, data) {
state.producten = data
}
}
export const getters = {
getProduct(state, id) {
console.log(id)
return state.producten.filter(product => product.id = id)
}
}
export const actions = {
async fetchProducts({ commit }) {
await axios.get('/api/products')
.then(res => {
var data = res.data
commit('setProducts', data)
})
.catch(err => console.log(err));
}
}
What works is creating the state, but when i try to use the getter something goes wrong.
As you can see i console.log() the id given to it. Which logs the following:
I also get the error: client.js?06a0:103 Error: [vuex] do not mutate vuex store state outside mutation handlers.
Which I'm not doing as far as I know?
**Note: **these errors get logged as much as the length of my state array is.
From the Vuex documentation:
Vuex allows us to define "getters" in the store. You can think of them as computed properties for stores. Like computed properties, a getter's result is cached based on its dependencies, and will only re-evaluate when some of its dependencies have changed.
Like computed, getters does not support having arguments.
But there is a way to have "method-style access" to a getter: https://vuex.vuejs.org/guide/getters.html#property-style-access
You can also pass arguments to getters by returning a function. This is particularly useful when you want to query an array in the store:
getters: {
// ...
getTodoById: (state) => (id) => {
return state.todos.find(todo => todo.id === id)
}
}
store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }
Note that getters accessed via methods will run each time you call them, and the result is not cached.

Understanding State and Getters in Nuxt.js: Getters won't working

i'm new to Vue and Nuxt and i'm building my first website in Universal mode with these framework.
I'm a bit confused on how the store works in nuxt, since following the official documentation i can't achieve what i have in mind.
In my store folder i have placed for now only one file called "products.js", in there i export the state like this:
export const state = () => ({
mistica: {
id: 1,
name: 'mistica'
}
})
(The object is simplified in order to provide a cleaner explanation)
In the same file i set up a simple getter, for example:
export const getters = () => ({
getName: (state) => {
return state.mistica.name
}
})
Now, according to the documentation, in the component i set up like this:
computed: {
getName () {
return this.$store.getters['products/getName']
}
}
or either (don't know what to use):
computed: {
getName () {
return this.$store.getters.products.getName
}
}
but when using "getName" in template is "undefined", in the latter case the app is broken and it says "Cannot read property 'getName' of undefined"
Note that in the template i can access directly the state value with "$store.state.products.mistica.name" with no problems, why so?
What am i doing wrong, or better, what didn't i understand?
Using factory function for a state is a nuxt.js feature. It is used in the SSR mode to create a new state for each client. But for getters it doesn't make sense, because these are pure functions of the state. getters should be a plain object:
export const getters = {
getName: (state) => {
return state.mistica.name
}
}
After this change getters should work.
Then you can use the this.$store.getters['products/getName'] in your components.
You can't use this.$store.getters.products.getName, as this is the incorrect syntax.
But to get simpler and more clean code, you can use the mapGetters helper from the vuex:
import { mapGetters } from "vuex";
...
computed: {
...mapGetters("products", [
"getName",
// Here you can import other getters from the products.js
])
}
Couple of things. In your "store" folder you might need an index.js for nuxt to set a root module. This is the only module you can use nuxtServerInit in also and that can be very handy.
In your products.js you are part of the way there. Your state should be exported as a function but actions, mutations and getters are just objects. So change your getters to this:
export const getters = {
getName: state => {
return state.mistica.name
}
}
Then your second computed should get the getter. I usually prefer to use "mapGetters" which you can implement in a page/component like this:
<script>
import { mapGetters } from 'vuex'
export default {
computed: {
...mapGetters({
getName: 'products/getName'
})
}
</script>
Then you can use getName in your template with {{ getName }} or in your script with this.getName.

With Vuex, why isn't mapGetters accepting the same syntax as mapState?

I have a Vue component that maps in state, mutations, actions, and getters from a Vuex store.
import {mapState, mapMutations, mapActions, mapGetters} from 'vuex'
export default {
name: 'DefaultLayout',
computed: {
...mapState({
settings: (state) => state.settings,
language: (state) => state.language
}),
...mapState([
'changeRouteTo'
]),
...mapGetters([
'isLoggedIn'
])
}
...
The problem is, I cannot get ...mapGetters to work with the explicit syntax like I do with the first instance of ...mapState above.
I've tried
...mapGetters({
isLoggedIn: (state) => state.getters.isLoggedIn
})
and
...mapGetters({
isLoggedIn: (state) => state.isLoggedIn
})
and
...mapGetters({
isLoggedIn: (state) => this.$store.getters.isLoggedIn
})
But only
...mapGetters([
'isLoggedIn'
])
seems to work.
To use an object in ...mapGetters the syntax is as follows:
...mapGetters({
isLoggedIn: 'isLoggedIn'
})
where the key is the name you want the getter to map to and the value is the name of the getter as a string
with mapGetters you should use getters to access some slice of the state for example in your store you will have something like this
const state = {
isLoggedIn:''
}
const getters = {
isLoggedIn(state) {
return state.isLoggedIn
}
}
export default {
state,
getters
}
and in your component you can access the isloggedIn property like this
computed: {
...mapGetters(['isLoggedIn'])
},
and now you have access to isLoggedIn property
because mapGetters gives access to the gitters the get functions that returns a slice of the store you dont have to rewrite the get function and pass the state to it that logic you should do it the in the getters this is there purpose
The above answers were all correct, though they don't answer the question "why"?
So the docs don't answer it either - it's a shame.
Let me give you my take:
VueX getters should already do whatever you need.
You see, VueX is meant for large applications. As such, there's a high chance the state or the state that is derived from the base state(getters) will be used in more than one place.
Getters already have access to the VueX state (as they are derived from the state!), they already have access to the other VueX getters too!
I'd say, if you find yourself needing to manipulate the getter, just create another getter that does just that - and simply import it.

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