How to access Vuex map helpers with Composition API - vue.js

I am using Composition API in Vue2. Can you tell me how to access mapState with composition API? I want to watch for state changes as well. Hence I would have to use it within setup function as well (not only in return). Thanks

The Vuex map helpers aren't supported (yet?) in the Vue 2 or Vue 3 composition API, and this proposal for them has been stalled for a while.
You'll have to manually create a computed like in the docs:
const item = computed(() => store.state.item);
A more complete example:
import { computed } from 'vue';
import { useStore } from 'vuex';
export default {
setup() {
const store = useStore();
const item = computed(() => store.state.item);
return {
item
};
}
}

For me the trick was using the vuex-composition-helper npm package.
https://www.npmjs.com/package/vuex-composition-helpers
import { useState, useActions } from 'vuex-composition-helpers';
export default {
props: {
articleId: String
},
setup(props) {
const { fetch } = useActions(['fetch']);
const { article, comments } = useState(['article', 'comments']);
fetch(props.articleId); // dispatch the "fetch" action
return {
// both are computed compositions for to the store
article,
comments
}
}
}

Related

Upgraded to Vue 2.7 and now getting a bunch of warnings: [Vue warn]: Vue 2 does not support readonly arrays

Background
I recently upgraded from Vue v2.6.14 to Vue 2.7 by following this guide: https://blog.vuejs.org/posts/vue-2-7-naruto.html.
I made some changes (e.g., removing #vue/composition-api and vue-template-compiler, upgrading to vuex-composition-helpers#next, etc.).
Problem
The application loads for the most part, but now I get a ton of console errors:
[Vue warn]: Vue 2 does not support readonly arrays.
It looks like even just console.log(workspaces.value); (see code below) raises the warning.
Question
How do I resolve this issue?
Thank you!
Code
<script lang="ts">
import {
defineComponent,
onMounted,
computed,
} from 'vue';
import { createNamespacedHelpers } from 'vuex-composition-helpers';
import {
modules,
actionTypes,
getterTypes,
} from '#/store/types';
import _ from 'lodash';
const workspaceModule = createNamespacedHelpers(modules.WORKSPACE_MODULE);
export default defineComponent({
setup() {
const { newWorkspace, listWorkspaces } = workspaceModule.useActions([
actionTypes.WorkspaceModule.NEW_WORKSPACE,
actionTypes.WorkspaceModule.LIST_WORKSPACES,
]);
const { workspaces } = workspaceModule.useGetters([
getterTypes.WorkspaceModule.GET_WORKSPACES,
]);
onMounted(async () => {
await listWorkspaces({
Archived: false,
Removed: false,
});
console.log(workspaces.value);
});
return {
/*
workspacesSorted: computed(() => {
return _.orderBy(workspaces.value, ['LastUpdated'], ['desc']);
}),
*/
}
}
});
</script>
src/store/modules/workspace/getters.ts
import { GetterTree } from 'vuex';
import { WorkspaceState } from './types';
import { RootState } from '../../types';
import { getterTypes } from '../../types';
export const getters: GetterTree<WorkspaceState, RootState> = {
[getterTypes.WorkspaceModule.GET_WORKSPACES](context: WorkspaceState) {
return context.Workspaces;
},
[getterTypes.WorkspaceModule.GET_ALL_WORKSPACES](context: WorkspaceState) {
return context.AllWorkspaces;
}
}
src/store/modules/workspace/actions.ts
export const actions: ActionTree<WorkspaceState, RootState> = {
async [actionTypes.WorkspaceModule.LIST_WORKSPACES]({ commit }, payload: ListWorkspace) {
const wss = await list(payload.Archived, payload.Removed);
wss.forEach((ws) => {
ws.Archived = payload.Archived;
ws.Removed = payload.Removed;
});
commit(mutationTypes.WorkspaceModule.SET_WORKSPACES, wss);
},
};
src/store/modules/workspace/actions.ts
export const mutations: MutationTree<WorkspaceState> = {
[mutationTypes.WorkspaceModule.SET_WORKSPACES](ctx: WorkspaceState, wss: Workspace[]) {
ctx.Workspaces = wss;
},
};
src/service/useWorkspace.ts
const list = async(archived: boolean, removed: boolean) => {
const res = await get<Workspace[], AxiosResponse<Workspace[]>>('/workspace/list', {
params: {
archived,
removed,
}
});
return success(res);
};
When I call store.state.WorkspaceModule.Workspaces directly (either in the console or in computed), I get no errors:
import { useStore } from '#/store';
export default defineComponent({
setup() {
const store = useStore();
onMounted(async () => {
await listWorkspaces({
Archived: false,
Removed: false,
});
console.log(store.state.WorkspaceModule.Workspaces);
});
return {
workspacesSorted: computed(() =>
store.state.WorkspaceModule.Workspaces
),
}
}
});
This might be because workspaces is based on a getter, which are read-only. As mentioned in the blog you were referring to, readonly is not supported for arrays in Vue 2.7:
readonly() does create a separate object, but it won't track newly added properties and does not work on arrays.
It was (partially) supported for arrays in the Vue 2.6 Composition Api Plugin though:
readonly() provides only type-level readonly check.
So that might be causing the error. If it is mandatory for you, you might need to upgrade to vue3, or stick with 2.6 for a while. The composition Api plugin is maintained until the end of this year...
A workaround may be to skip the getter and access the state directly, since it is a quite simple getter which only returns the current state of Workspaces.
Hope this helps.

vuex state not updating UI on change

I am in the process of converting a vue2 to vue3 project and noticed my UI isn't updating when objects from my vuex store are updating. Here is how I create my store:
store/index.js
import {mutations} from './mutations';
import {createStore} from 'vuex'
export default createStore({
state() {
return {
...
}
},
mutations
});
mutations.js
export const mutations = {
narrative(state, v) {
state.narrative = v;
}
};
app.js
import { createApp } from 'vue';
import store from './store/index';
const app = createApp({
mixins: [
require('./mixins/base')
]
}).use(store)
So when I mutate one of the vuex objects, I write to the console log immediately and see the data has changed
let narrative = _.find(this.$store.state.narratives, ['id', this.selectedNarrativeId]);
if (narrative) {
console.log(narrative.id); // PRINTS CORRECT UPDATED ID
this.$store.commit('narrative', narrative);
console.log(this.$store.state.narrative.id); // PRINTS CORRECT UPDATED ID
}
But the UI does not change. However, if I used a computed property, the UI updates immediately. What am I doing wrong with the vuex store?
computed: {
currentNarrative() {
let narrative = _.find(this.$store.state.narratives, ['id', this.selectedNarrativeId]);
if (narrative) {
return narrative;
}
return {};
},
}
Versions
vue 3.2.33
vuex 4.0.2
Replacing the require by an import + rebooting the machine fixed the issue, maybe some broken was still running on the server.

Vue 3 composition API with updating refs

I am passing a ref value to a composable function, updateableSetting. This has an initial value, settingA, but can be updated by the user. When updated, us it possible to have useFeature run again and return an updated feature value?
export default defineComponent({
setup() {
const updateableSetting = ref('settingA')
const { feature } = useFeature(updateableSetting.value)
}
})
Sure. Use a computed property
import { ref, defineComponent, computed} from 'vue'
const useFeature = (initialRef) => {
const feature = computed(() => initialRef.value + ' - I am always up to date!')
return {
feature
}
}
export default defineComponent({
setup() {
const updateableSetting = ref('settingA')
//make sure you don't pass .value here - pass the whole ref object instead
const { feature } = useFeature(updateableSetting)
return { feature }
}
})
If you mean "run a function everytime updatedValue changes", you can use
watch(
[updatedValue],
() => {console.log('updatedValue changed! doing some calculations...')}
)
I had same problem when using composables in nuxt 3.
In nuxt 3 new reactive state is available called useState. try useState instead of ref.
for more information see nuxt 3 document: useState nuxt3

How to get item by Id using Vue 3 Composition API using Axios

Im struggling using Axios and useRoute using Axios with Composition API. Here is the code on how to do it in using the Option API, how do I recreate it, the Vue-router docs not well documented at all right now.
async created() {
const result = await axios.get(`https://localhost:5001/api/artists/${this.$route.params.id}`
);
const artist = result.data;
this.artist = artist;
},
To convert that code to Composition API:
created() hook is effectively the same timing as setup(), so put that code in setup().
this.$route can be accessed via useRoute() (from vue-router#4).
artist can be declared as a data ref, returning it from setup() if used in the template.
To reactively fetch data from the API based on the id parameter, use watch on route.params.id. This watch call returns a function that stops the watcher, which is useful if you need to conditionally unwatch the reference.
import { useRoute } from 'vue-router'
import { ref, watch } from 'vue'
export default {
// 1
setup() {
const route = useRoute() // 2
const artist = ref(null) // 3
// 4
const unwatch = watch(() => route.params.id, (newId, oldId) => {
const result = await axios.get(`https://localhost:5001/api/artists/${newId}`)
artist.value = result.data
// run only once
unwatch()
})
return {
artist
}
}
}

How to use shorter path to get vuex contents?

In my vuex /store/state.js I have an export default that looks like this:
export default {
foo: {
bar:{
tar: {
info: 42
}
}
}
}
So, whenever I want to access info, I usually do in my methods like this;
methods: {
getInfo () {
return this.$store.state.foo.bar.tar.info
}
}
This is just for a demo purpose, and mine is actually a bit worse, but I ended up doing the same so, I tried minimize the code using a computed prop:
computed: {
info () {
return this.$store.state.foo.bar.tar.info
}
}
Now, I just call info but still, not sure if there is a better way to get values, because sometimes I just need to call info only one in a page, so I have to use the full path or create a computed property for it.
Is there any other way to do this
I always separate vuex into separated modules. For instance if you have store for foo module. I will create file named foo.js which contains
const fooModule = {
state: {
foo: {
bar: {
tar: {
info: 42
}
}
}
},
getters: {
info (state) {
return state.foo.bar.tar.info
}
},
mutations: {
setInfo (state, payload) {
state.foo.bar.tar.info = payload
}
},
actions: {
getInfo ({commit}, payload) {
commit('setInfo', payload)
}
}
}
export default fooModule
Then in your main index vuex, import the module like this way
import Vue from 'vue'
import Vuex from 'vuex'
import fooModule from './foo.js'
Vue.use(Vuex)
const store = new Vuex.Store({
modules: {
fooModule
}
})
export default store
Then if you wanna get info, you just write your code like this
import { mapGetters } from 'vuex';
export default {
computed: {
...mapGetters([
'getInfo'
])
}
}
#jefry Dewangga has the the right idea but introducing mapGetters is unnecessary.
VueX by default includes namespacing for modules which allows us to load multiple modules into a store and then reference them with or without namespacing them and it'll figure the rest out.
For Instance if we have the structure of
|-- store
|-- Modules
|-- module1.js
|-- module2.js
|-- module3.js
|-- index.js
We can use index in such a way to bind all of our modules into our Vuex store doing the following:
import Vue from 'vue'
import Vuex from 'vuex'
import modules from './modules'
Vue.use(Vuex)
export default new Vuex.Store({
modules
})
An example of our module1 could be:
const state = {
LoggedIn: true
}
const mutations = {
LOGIN(state) {
state.LoggedIn = true;
},
LOGOFF(state) {
state.LoggedIn = false;
}
}
const actions = {}
export default {
state,
mutations,
actions
}
This in turn gives us the ability to say:
this.$store.commit('LOGIN');
Note that we haven't used any namespacing but as we haven't included any duplicate mutations from within our modules were absolutely fine to implicitly declare this.
Now if we want to use namespacing we can do the following which will explicitly use out module:
this.$store.module1.commit('LOGIN');
MapGetters are useful but they provide a lot of extra overhead when we can neatly digest out modules without having to continuously map everything, unless well we find the mapping useful. A great example of when MapGetters become handy is when we are working many components down in a large project and we want to be able to look at our source without having to necessarily worry about the frontend implementation.