WEBPACK_IMPORTED_MODULE_1__.default.set is not a function - javascript

I havent been able to figure out what the problem is here. I am using vue 3.
I trye to add an obejct to another object inside of the store state. I can add it to the firebase console, but the only thing that has not been solved yet is how to add it to the store in the state.coaches as an object within an object. In this way I would be able to display the list of object into the view of the screen.
//store-coach.js
import Vue from 'vuex'
import { uid, Notify } from 'quasar'
import firebase from 'boot/firebase'
const state = {
coaches: {
}
}
const mutations = {
addCoach(state, coach) {
Vue.set(state.coaches, coach.id, coach.coach)
}
}
const actions = {
fbReadDataCoaches({ commit }) {
let coachesfb = firebase.database().ref('coaches')
//child added
coachesfb.on('child_added',snapshot => {
let coachfb = snapshot.val()
let payload = {
id: snapshot.key,
coach: coachfb
}
commit('addCoach', payload)
})
},
fbaddCoach({}, payload){
let coachRef = firebase.database().ref('coaches/' + payload.id)
coachRef.set(payload.coach, error =>{
if(!error){
Notify.create('Coach added!!')
}
})
}
}
//index.js
import Vuex from 'vuex'
import coaches from './store-coach'
export default function (/* { ssrContext } */) {
const Store = new Vuex.Store({
modules: {
coaches
}
})
return Store
}
The error that I get is when
Vue.set(state.coaches, coach.id, coach.coach) is fired
Uncaught TypeError: vuex__WEBPACK_IMPORTED_MODULE_3__.default.set is not a function
thanks in advance!
Appreciate your time!

In first file (store-coach.js), change:-
From -
import Vue from 'vuex'
To -
import Vue from 'vue'
As .set method is available in vue package. Its not available in vuex package that is why you are getting this error. Documentation reference.

Related

Using `useStore` API with vuex 4.x

Follow the official example to export your own useStore, and then use it in the component.
import { createStore, Store, useStore as baseUseStore } from 'vuex';
export const key: InjectionKey<Store<RootState>> = Symbol();
export function useStore() {
return baseUseStore(key);
}
use in the component
setup() {
const store = useStore();
const onClick = () => {
console.log(store)
store.dispatch('user/getUserInfo');
}
return {
onClick,
}
},
After running, store is undefined.
It can be obtained normally when I use it in the methods attribute
methods: {
login() {
this.$store.dispatch('user/getToken')
}
}
why? how to fix it
In that simplifying useStore usage tutorial, you still need to register the store and key in main.ts as they did. You will get undefined if you don't do this:
// main.ts
import { store, key } from './store'
const app = createApp({ ... })
// pass the injection key
app.use(store, key)
The reason is that baseUseStore(key) has no meaning until that's done.

Trying to test vue component that use mapState from vuex

Currently trying to test a vue component that is using the vuex ...mapState method but just by bringing it into the component fails my tests.
This is the current error i'm getting:
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import _Object$defineProperty from "../../core-js/object/define-property";
This is my component I'm trying to test.
SimpleComponent.vue
<template>
<h1> Hello!!!</h1>
</template>
<script>
import mapState from 'vuex';
export default {
computed: {
...mapState(["users"])
}
}
</script>
<style>
</style>
This is my store but simplified for testing purposes.
store.js
import Vue from "vue";
import Vuex from "vuex";
const fb = require("./firebaseConfig.js");
Vue.use(Vuex);
fb.auth.onAuthStateChanged(user => {
if (user) {
store.commit('setCurrentUser', user)
// realtime updates from our posts collection
fb.usersCollection.onSnapshot(querySnapshot => {
let userArray = []
querySnapshot.forEach(doc => {
let user = doc.data()
user.id = doc.id
userArray.push(user)
})
store.commit('setUsers', userArray)
})
}
})
export const store = new Vuex.Store({
state: {
users:[],
},
actions: {
clearData({ commit }) {
commit('setUsers', null);
},
},
mutations: {
setUsers(state, val){
state.users = val
},
},
});
And here is my test
SimpleComponentTest.spec.js
import { shallowMount, createLocalVue } from '#vue/test-utils';
import SimpleStore from '../../src/components/SimpleComponent.vue';
import Vuex from 'vuex';
const sinon = require('sinon');
const localVue = createLocalVue();
localVue.use(Vuex);
describe('SimpleComponent.vue', () => {
it('Is Vue Instance', () => {
const wp = shallowMount(SimpleComponent, { computed: { users: () => 'someValue' }, localVue });
expect(wp.isVueInstance()).toBe(true);
});
});
Im using Jest with Sinon for testing. I am a little confused on the proper way to set up the store in my test but this is one way I found when looking online.
The code base is a little bigger than what I am showing you but that is because after running into errors for hours I figured I needed the simplest piece of code to test that uses the ...mapState method and build it back up from there.
Any help would be greatly appreciated :)
Goal: To get a simple test to pass that tests a component that uses ...mapState([]) from vuex

Why is Vue not defined here?

Why am I getting Vue is not defined as an error here:
export default {
state: {
projects: {
loading: true,
failed: false,
lookups: [],
selectedId: 0
}
},
mutations: {
loadingProjectLookups (state, payload) {
state.projects.loading = true;
state.projects.failed = false;
}
},
actions: {
loadProjectLookups (context) {
return new Promise((resolve) => {
// VUE NOT DEFINED HERE:
Vue.http.get('https://my-domain.com/api/projects').then((response) => {
context.commit('updateProjectLookups', response.data);
resolve();
},
response => {
context.commit('failedProjectLookups');
resolve();
});
});
}
}
}
This is my vue config:
'use strict';
import Vue from 'vue';
import Vuex from 'vuex';
var VueResource = require('vue-resource');
/* plugins */
Vue.use(Vuex);
Vue.use(VueResource);
/* stores */
import importPageStore from './apps/import/import-page-store';
/* risk notification import */
import ImportApp from './apps/import/import-app.vue';
if (document.querySelector("#import-app")) {
var store = new Vuex.Store(importPageStore);
new Vue({
el: '#import-app',
store,
render: h => h(ImportApp)
});
}
My understanding is that Vue is defined globally and I cannot see why it is not defined. If I add import Vue from 'vue' to my store then I get a message that http is not defined. So I need to work out why Vue appears not to be available globally as I shouldn't have to do this.
I am using webpack to build my vue components. I have other pages rendered using this methodology and they work just fine. But this one does not? I am honestly stumped as to why as I cannot see any differences. The page renders and works. I can see that Vue is working. How can it be undefined?
In a component, you can use this.$http, however, in your store you will need to import Vue every time.
What you can do, is create a service folder and import Vue there. Then just reference your service in the store file.
There's an example here https://github.com/vuejs/vuex/issues/85
Which suggests something like this:
/services/auth.js
import Vue from 'vue'
export default {
authenticate(request) {
return Vue.http.post('auth/authenticate', request)
.then((response) => Promise.resolve(response.data))
.catch((error) => Promise.reject(error));
},
// other methods
}
In your store file:
import { AUTHENTICATE, AUTHENTICATE_FAILURE } from '../mutation-types'
import authService from '../../services/auth'
export const authenticate = (store, request) => {
return authService.authenticate(request)
.then((response) => store.dispatch(AUTHENTICATE, response))
.catch((error) => store.dispatch(AUTHENTICATE_FAILURE, error));
}
// other actions
This is how VueResource extends Vue prototype.
Object.defineProperties(Vue.prototype, {
// [...]
$http: {
get() {
return options(Vue.http, this, this.$options.http);
}
},
// [...]
});
}
VueResource handles the promise itself. Thus, you don't need to wrap the requests in promises. You can use Promise.all() later. But I don't see multiple requests so you just use the get request.
Reference: Using promise in vue-resource
I hope, this would solve your issue with that error.

Get vuex module state in another module action

I'm a little bit confused with vuex store component.
How should I obtain state of another module?
I tried a different ways to get data from store and always got Observer object. What is the correct way to knock knock to observer?
If I try to get anything from this object directly, like rootState.user.someVariable then I got undefined response.
Don't have a problem getting state from components.
Edit. Add code
User module
import * as Constants from './../../constants/constants'
import * as types from '../mutation-types'
import axios from 'axios'
const state = { user: [] }
const getters = {
getUser: state => state.user
}
const actions = {
getUserAction ({commit}) {
axios({method: 'GET', 'url': Constants.API_SERVER + 'site/user'})
.then(result => {
let data = result.data
commit(types.GET_USER, {data})
}, error => {
commit(types.GET_USER, {})
console.log(error.toString())
})
}
}
const mutations = {
[types.GET_USER] (state, {data}) {
state.user = data
}
}
export default { state, getters, actions, mutations }
Mutatinos
export const GET_LANGS = 'GET_LANGS'
export const GET_USER = 'GET_USER'
Store
import Vuex from 'vuex'
import Vue from 'vue'
import user from './modules/user'
import lang from './modules/lang'
Vue.use(Vuex)
const store = new Vuex.Store({
modules: {
user,
lang
}
})
Main app
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store/index'
Vue.config.productionTip = false
new Vue({
el: '#app',
router,
store,
template: '<App/>',
components: { App }
})
Lang module, here is the place where I'm trying get store
import * as types from '../mutation-types'
import {axiosget} from '../../api/api'
const state = { langList: [] }
const getters = {
getLangs: state => state.langList
}
const actions = {
// this two action give me similar result
getLangsAction (context) {
axiosget('lang') // described below
},
getAnotherLangsAction (context) {
console.log(context.rootState.user) <----get Observer object
}
}
const mutations = {
[types.GET_LANGS] (state, {data}) {
state.langList = data
}
}
export default { state, getters, actions, mutations }
axiosget action, api module
import * as Constants from './../constants/constants'
import store from '../store/index'
import axios from 'axios'
export const axiosget = function (apiUrl, actionSuccess, actionError) {
console.debug(store.state.user) // <----get Observer object, previously described
// should append user token to axios url, located at store.state.user.access_token.token
axios({method: 'GET', 'url': Constants.API_URL + apiUrl
+ '?access_token=' + store.state.user.access_token.token})
.then(result => {
let data = result.data
// todo implement this
// }
}, error => {
if (actionError && actionError === 'function') {
// implement this
}
})
}
Component, that call dispatcher. If i get state via mapGetters in computed properties - there is no problems
<template>
<div>
{{user.access_token.token}}
</div>
</template>
<script>
import { mapGetters } from 'vuex'
export default {
name: 'ArticlesList',
computed: mapGetters({
user: 'getUser'
}),
created () {
this.$store.dispatch('getLangsAction')
this.$store.dispatch('getAnotherLangsAction')
}
}
</script>
What I'm trying to do in this code - get user access token in main site (after login) and all further manipulations with data will be produced via api host.
Let's say you want to fetch state an attribute userId from object userDetails in Vuex store module user.js.
userDetails:{
userId: 1,
username: "Anything"
}
You can access it in following way in action
authenticateUser(vuexContext, details) {
userId = vuexContext.rootState.user.userDetails.userId;
}
Note: After rootState and before file name user, add the path to the store module file if it is inside nested folders.

vuex and axios debugging

I'm going crazy, I have a working api that sends data, I connected it to a VueJS app and it was working fine. I'm trying to implement Vuex and I'm stuck. Here's my store.js file
import Vue from 'vue';
import Vuex from 'vuex';
import axios from 'axios'
Vue.use(Vuex);
const state = {
message: "I am groot",
articles: []
}
const getters = {
getArticles: (state) => {
return state.articles;
}
}
const actions = {
getArticles: ({ commit }, data) => {
axios.get('/articles').then( (articles) => {
commit('GET_ARTICLES', articles);
console.log(articles); // Trying to debug
}, (err) => {
console.log(err);
})
}
}
const mutations = {
GET_ARTICLES: (state, {list}) => {
state.articles = list;
}
}
const store = new Vuex.Store({
state,
getters,
mutations,
actions,
mutations
});
console.log(store.state.articles); // this lines works but data is empty
export default store
The console.log within axios call doesn't run and store.state.articles is empty. I must be missing something. I'm just trying to console the articles data on page load...
Please help, I'm near insanity :)
Component :
<template>
<div class="container">
<h1>Test component yo !</h1>
<p>{{ message }}</p>
</div>
</template>
<script>
export default {
name: 'Test',
computed: {
message() {
return this.$store.state.message
}
},
mounted: () => {
this.$store.dispatch('getArticles')
}
}
</script>
App.js :
import Vue from 'vue';
import ArticlesViewer from './articles_viewer.vue';
import UserArticles from './user_articles.vue';
import App from './app.vue'
import store from './store'
new Vue({
el: '#app-container',
store,
render: h => h(App)
})
You define the mounted lifecycle hook of your component using an arrow function.
As per the documentation:
Don’t use arrow functions on an instance property or callback (e.g. vm.$watch('a', newVal => this.myMethod())). As arrow functions are bound to the parent context, this will not be the Vue instance as you’d expect and this.myMethod will be undefined.
You should define it like so:
mounted: function () {
this.$store.dispatch('getArticles');
}
Or, use the ECMAScript 5 shorthand:
mounted() {
this.$store.dispatch('getArticles');
}
Now, your dispatch method will be called correctly, populating your articles array.

Categories

Resources