Storybook - Set and get Vuex state - vue.js

I try to use Storybook in a Nuxt project. Story file looks similar to
import Chip from '~/components/UI/Chip.vue'
import store from '#/storybook/store';
export default {
title: 'Chips',
component: Chip,
}
const Template = (args, { argTypes }) => ({
store: store,
props: Object.keys(argTypes),
components: { Chip },
});
export const Primary = Template.bind({})
Primary.args = {
color: 'background-darken-4'
}
And Store
import Vue from 'vue'
import Vuex from 'vuex'
import themes from '~/components/PassporterUI/themes/index'
import ThemeCollection from '~/models/ThemeCollection'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
theme: undefined,
},
mutations: {
theme(state) {
const defaultTheme = themes.find(
(theme) => theme.name === 'passporter-light'
)
if (defaultTheme) {
state.theme = new ThemeCollection({
current: defaultTheme,
list: themes,
})
}
},
},
actions: {
setTheme({ commit }) {
commit('theme', state.theme)
},
},
})
Returns this multiple errors
Do, anyone knows what is the right way to fix this?

Related

vuex unknown mutation type: setPatient

I'm using vue 3 with composition api and vuex 4, I've done it this way before but now its throwing that error.
Here's my store/index.js
import { createStore } from "vuex";
export const store = new createStore({
state: {
patient: [],
},
mutations: {
setPatient(state, payload) {
state.patient = payload;
},
},
getters: {
getPatient(state) {
return state.patient;
},
getAppointment(state) {
return state.patient.appointments;
},
},
})
app.js
require('./bootstrap');
import { createApp, h } from 'vue';
import { createInertiaApp } from '#inertiajs/inertia-vue3';
import { InertiaProgress } from '#inertiajs/progress';
import {store} from './Store'
const { RayPlugin } = require('vue-ray');
window.$ = window.jQuery = require("jquery");
const appName = window.document.getElementsByTagName('title')[0]?.innerText || 'Laravel';
createInertiaApp({
title: (title) => `${title} - ${appName}`,
resolve: (name) => require(`./Pages/${name}.vue`),
setup({ el, app, props, plugin }) {
return createApp({ render: () => h(app, props) })
.use(plugin)
.use(store)
.use(RayPlugin, { interceptErrors: true, host: '127.0.0.1', port: 23517 })
.mixin({ methods: { route } })
.mount(el);
},
});
InertiaProgress.init({ color: '#4B5563' });
And following the documentation, on my component I did the following:
import { useStore } from 'vuex'
import {onMounted, reactive, ref} from "vue";
export default {
props: {
patient: {
type: Object,
required: true
}
},
setup(props) {
const store = useStore();
onMounted(() => {
store.commit('setPatient', props.patient);
})
}
}
So far I've done this before, but using the composition api is new for me, so I couldn't find where the error is

Using vuex PersistedState with vuex modules

I want to use PersistedState https://github.com/robinvdvleuten/vuex-persistedstate with vuex but i can't get to setup correctly.
I have this module inside the store directory
export const auth = {
namespaced: true,
state: {
},
getters: {
countLinks: state => {
return state.links.length
}
},
mutations: {
SET_LINKS: (state, links) => {
state.links = links;
},
//Synchronous
ADD_LINK: (state, link) => {
state.links.push(link)
},
REMOVE_LINK: (state, link) => {
state.links.splice(link, 1)
},
REMOVE_ALL: (state) => {
state.links = []
}
},
actions: {
//Asynchronous
removeLink: (context, link) => {
context.commit("REMOVE_LINK", link)
},
removeAll ({commit}) {
return new Promise((resolve) => {
setTimeout(() => {
commit('REMOVE_ALL')
resolve()
}, 1500)
})
}
}
}
I have named this àuth.js
This is my index.js file also inside store directory
import { createStore } from 'vuex'
import createPersistedState from "vuex-persistedstate"
import { auth } from './auth'
const dataState = createPersistedState({
paths: ['data']
})
const store = createStore({
modules: {
auth
},
plugins: [dataState]
})
I have a total of 7 modules i would like to load and use in various places in my application. To kick things off i just want to load auth module and use it in my home.vue page
This is the script section of my home.vue
import Footer from '#/components/Footer.vue'
import Header from '#/components/Header.vue'
import { mapGetters} from 'vuex'
import store from '../store';
export default {
name: 'Home',
components: {
Footer,Header
},
mounted () {
var links = ['http://google.com','http://coursetro.com','http://youtube.com'];
store.commit('SET_LINKS', links);
},
computed: {
...mapGetters([
'countLinks'
]),
}
}
This is my main.js file
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import i18n from './i18n'
import FlagIcon from 'vue-flag-icon'
import {store} from './store';
createApp(App).use(i18n).use(FlagIcon).use(store).use(router).mount('#app')
When i npm run serve, i get the error
10:7 error 'store' is assigned a value but never used
no-unused-vars
How should i correct this to be able to use auth.js module anywhere in my application?

IONIC + Vue.js not working getters in VUEX

Hello developers I'm working with Ionic and Vue+Vuex in this app, but eventually, I can't access my state from my getters for some reason.
As usually the management state is settled for that purpose with actions getters, mutations, and state.
import { createStore } from "vuex";
const urlLogin = "http://localhost:3006/auth";
const urlUser = "http://localhost:3006/user";
const store = createStore({
state() {
return {
userRegisteredState: false,
allUsersState: [],
};
},
mutations: {
commit_get_all_users(state, payload) {
console.log(payload);
return (state.allUsersState = payload);
},
},
getters: {
getterGetAllUsers(state) {
console.log(state);//checking all state (See image )
console.log(state.allUsersState)//checking only the item I want to consume from state (See image )
return state.allUsersState;
},
},
actions: {
//=================================================================
//============================================================
async getAllUsers({ commit }) {
fetch(`${urlUser}/get/all/users`, {
method: "GET",
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "http://localhost:8100",
},
})
.then((result) => {
return result.json();
})
.then((result) => {
console.log(result);
commit("commit_get_all_users", result);
})
.catch((error) => {
console.log(error);
error;
});
},
},
});
export default store;
then on my component , in this case that one referring to get all users I set this logic:
<template>
...some tags...
</template>
<script>
import { mapActions, mapGetters } from "vuex";
export default {
name: "AllUsersComponent",
data() {
return {
allUsers: [],
};
},
methods: {
...mapActions(["getAllUsers"]),
getAllUsersFront() {
this.$store.dispatch("getAllUsers");
},
...some methods....
},
computed: {
...mapGetters(["getterGetAllUsers"]),
getterGetAllUsersFunction() {
console.log(this.$store.getters.getterGetAllUsers);
return this.$store.getters.getterGetAllUsers;
},
},
async mounted() {
this.getAllUsersFront();
},
created() {
this.getAllUsersFront();
this.getterGetAllUsersFunction;
console.log(this.getterGetAllUsersFunction);
},
watch: {},
};
</script>
<style>
</style>
On my main.js file store is imported according to IONC in this way
import { createApp } from "vue";
import './gapi.js'
import App from "./App.vue";
import router from "./router";
import store from "./store/index"; //importando vuex
import loginComponentTag from "./components/Login";
import allUsersComponentTag from "./components/all-users-component"
// import GoogleSignInButton from 'vue-google-signin-button-directive'
import { IonicVue } from "#ionic/vue";
/* Core CSS required for Ionic components to work properly */
import "#ionic/vue/css/core.css";
/* Basic CSS for apps built with Ionic */
import "#ionic/vue/css/normalize.css";
import "#ionic/vue/css/structure.css";
import "#ionic/vue/css/typography.css";
/* Optional CSS utils that can be commented out */
import "#ionic/vue/css/padding.css";
import "#ionic/vue/css/float-elements.css";
import "#ionic/vue/css/text-alignment.css";
import "#ionic/vue/css/text-transformation.css";
import "#ionic/vue/css/flex-utils.css";
import "#ionic/vue/css/display.css";
/* Theme variables */
import "./theme/variables.css";
const app = createApp(App)
.use(IonicVue)
.use(store)
.use(router)
app.component("LoginComponent", loginComponentTag);
app.component("AllUsersComponent",allUsersComponentTag)
router.isReady().then(() => {
app.mount("#app");
});
And my vue.config.js is settled in this way:
module.exports = {
devServer: {
proxy: "http://localhost:8100",
},
};
I checked my logs and eventually.
Literally, the situation is that despite having my state populated with data, unless I retrieve the whole state, I can't retrieve a particular item from it, cause the response is nothing.
Is there any configuration I'm omitting in this process I need to have in mind?

vuex module namespace not found in mapActions(): taskModule/?

Hello my application starts growing so i decided to call in vuex(for the first time) but i can't get it to work when i call actions/mutations of a module
my taskModule
const state = () => ({
newTask : false,
tasks: []
})
const getters = {}
const actions = {
test() {
console.log('EYOOO IT WORKSS')
},
}
const mutations = {}
export default {
namespaced: true,
state,
getters,
actions,
mutations
}
my store
import { createStore } from 'vuex'
import taskModule from '../store/modules/tasks'
export default createStore({
state: {
taskModule
},
})
my component js
export default {
components: {
Button,
TaskList,
NewTask,
},
computed: mapState({
newTask: (state) => state.taskModule.state().newTask,
tasks: (state) => state.taskModule.state().tasks,
}),
methods: {
...mapActions("taskModule",["test"]),
newTask(val) {
this.$store.dispatch("taskModule/test")
console.log(val);
},
},
};
when i call newTask i get the error
Since you have a module you need to change :
export default createStore({
state: {
taskModule
},
})
To :
export default createStore({
modules: {
taskModule
},
})
https://next.vuex.vuejs.org/guide/modules.html

Why Vuex-persist doesn't store anything in localStorage?

So, in my project (Vue-cli + TypeScript) I need to store user data to locaStorage. For this purpose I decide to use vuex-persist (npm plugin) alongside with vuex. But in DevTool, in localStorage doesn't appear anything. What is wrong in my code. Thank you in advance.
In precedent project I already used this combination of tools, and they work fine. In this project I use the same configuration, and it doesn't work . And this is the most strange thing.
This is StructureModule.ts
import { ActionTree, MutationTree, GetterTree, Module } from "vuex";
const namespaced: boolean = true;
interface IDataStructure {
name: string;
type: string;
description: string;
}
interface IStructureState {
name: string;
description: string;
props: IDataStructure[];
}
export interface IState {
structures: IStructureState[];
}
export const state: IState = {
structures: [
{
name: "",
description: "",
props: [
{
name: "",
type: "",
description: "",
},
],
},
],
};
export const actions: ActionTree<IState, any> = {
addNewDataStructure({ commit }, payload: IStructureState): void {
commit("ADD_DATA_STRUCTURE", payload);
},
updateDataStructure({ commit }, payload: IStructureState): void {
commit("UPDATE_EXISTING_DATA_STRUCTURE", payload);
},
clearDataStructure({ commit }, { name }: IStructureState): void {
commit(" CLEAR_DATA_STRUCTURE", name);
},
};
export const mutations: MutationTree<IState> = {
ADD_DATA_STRUCTURE(state: IState, payload: IStructureState) {
if (state.structures[0].name === "") {
state.structures.splice(0, 1);
}
state.structures.push(payload);
},
CLEAR_DATA_STRUCTURE(state: IState, name: string) {
state.structures.filter((structure: IStructureState) => {
if (structure.name === name) {
state.structures.splice( state.structures.indexOf(structure), 1);
}
});
},
UPDATE_EXISTING_DATA_STRUCTURE(state: IState, payload: IStructureState) {
state.structures.map((structure: IStructureState) => {
if (structure.name === payload.name) {
state.structures[state.structures.indexOf(structure)] = payload;
}
});
},
};
export const getters: GetterTree<IState, any> = {
dataStructureByName(state: IState, structName: string): IStructureState[] {
const structure: IStructureState[] = state.structures.filter((struct: IStructureState) => {
if (struct.name === structName) {
return struct;
}
});
return structure;
},
dataStructures(): IStructureState[] {
return state.structures;
},
};
export const StructureModule: Module<IState, any> = {
namespaced,
state,
mutations,
actions,
getters,
};
This is index.ts
import Vue from "vue";
import Vuex, { ModuleTree } from "vuex";
import VuexPersistence from "vuex-persist";
import { StructureModule , IState} from "./modules/StructureModule";
Vue.use(Vuex);
const storeModules: ModuleTree<IState> = {
StructureModule,
};
const vuexPersistentSessionStorage = new VuexPersistence({
key: "test",
modules: ["StructureModule"],
});
export default new Vuex.Store<any>({
modules: storeModules,
plugins: [vuexPersistentSessionStorage.plugin],
});
This is main.ts
import store from "#/store/index.ts";
import * as $ from "jquery";
import Vue from "vue";
import App from "./App.vue";
import router from "./router";
global.EventBus = new Vue();
(global as any).$ = $;
Vue.config.productionTip = false;
console.log(store);
new Vue({
router,
store,
render: (h) => h(App),
}).$mount("#app");
This is vue.config.js
module.exports = {
transpileDependencies: ["vuex-persist"],
};
This is store in vue-devtool
And this is dev-tool localStorage
I expect that in localstorage to appear an storage with key "test" with predefined values, but instead of this localStorage is empty.
As said in the guide
The only way to actually change state in a Vuex store is by committing
a mutation
https://vuex.vuejs.org/guide/mutations.html
I don't see any mutation in your code.
Otherwise, you should take a look at https://github.com/robinvdvleuten/vuex-persistedstate, it seems to be more popular, and I've been using it without any problem.
Usage is very simple : you just need to declare a plugin inside your store:
import createPersistedState from 'vuex-persistedstate'
const store = new Vuex.Store({
// ...
plugins: [createPersistedState()],
})
I found solution for this problem.
In my case i just remove namespaced from
export const StructureModule: Module<IState, any> = {
namespaced, <----- This
state,
mutations,
actions,
getters,
};
It seems namespaced should be used only if you have more than one module.