I'm new to Vue, i'm just trying to figure out how it is working.
I use router and i have a parent and a child element.
In the child, i have this simple HTML element in the child component:
<button #click="consoleLog">consoleLog</button>
The store at the main.js have this action:
export const store = new Vuex.Store({
state: {
userName: undefined,
password: undefined,
authenticated: false
},
mutations: {
changeUserNameMutation(state, userName) {
state.userName = userName;
},
changePasswordMutation(state, password) {
state.password = password;
Vue.axios.defaults.headers['Authorization'] = password;
},
changeAuthenticatedMutation(state, isAuthenticated) {
state.authenticated = isAuthenticated;
}
},
actions: {
changeUserName({ commit }, userName) {
commit('changeUserNameMutation', userName);
},
changePassword({ commit }, password) {
commit('changePasswordMutation', password);
Vue.axios.defaults.headers['Authorization'] = password;
},
changeAuthenticated({ commit }, isAuthenticated) {
commit('changeAuthenticatedMutation', isAuthenticated);
},
consoleLog({ commit }) {
console.log('sad');
}
}
Nothing more really in the main.js, just the new Vue call, Vue.use() calls and the imports.
In the child component, i have this actions:
methods: {
changeUserName(userName) {
store.dispatch('changeUserName', userName);
},
changePassword(password) {
store.dispatch('changePassword', password);
},
login() {
this.axios.get('http://localhost:3050/admin/login')
.then((data) => {
console.log(data);
})
.catch(() => {
console.log(data);
});
},
...mapActions(['consoleLog'])
}
The first 2 dispatch working, but when i hit the consoleLog method, it's says:
Cannot read property 'dispatch' of undefined at VueComponent.mappedAction
I've tried all other way to call ...mapActions(), but not working this way somehow for me.
(this is my first day in Vue, trying how it's working)
Related
Hi Stackoverflow Community,
I have a Vue.js application where a user can register. The registration is displayed in three different components. Register 1 (email, password), Register 2 (personal information) and Register 3 (preferences).
I implemented an api post request after the user press register on the first page according to bezkoder: https://www.bezkoder.com/vue-3-authentication-jwt/
What I am trying to do now is instead of register the user directly, I want to save the user data in my vuex store and send the api post request in Register 3 instead of Register 1, when I have all the user information.
Unfortunately, I am not able to create a new state in my store. This is my auth.module.js Code (store):
import AuthService from "../services/auth.service";
const user = JSON.parse(localStorage.getItem("user"));
const initialState = user
? { status: { loggedIn: true }, user }
: { status: { loggedIn: false }, user: null };
export const auth = {
namespaced: true,
state: initialState,
actions: {
login({ commit }, user) {
return AuthService.login(user).then(
(user) => {
commit("loginSuccess", user);
return Promise.resolve(user);
},
(error) => {
commit("loginFailure");
return Promise.reject(error);
}
);
},
logout({ commit }) {
AuthService.logout();
commit("logout");
},
register({ commit }, user) {
return AuthService.register(user).then(
(response) => {
commit("registerSuccess");
return Promise.resolve(response.data);
},
(error) => {
commit("registerFailure");
return Promise.reject(error);
}
);
},
},
mutations: {
loginSuccess(state, user) {
state.status.loggedIn = true;
state.user = user;
},
loginFailure(state) {
state.status.loggedIn = false;
state.user = null;
},
logout(state) {
state.status.loggedIn = false;
state.user = null;
},
registerSuccess(state) {
state.status.loggedIn = true;
},
registerFailure(state) {
state.status.loggedIn = false;
},
},
};
So I need to create a state for my userdata (email, password, preferences) and then an action and a method to save my userdata from Register 1 and 2.
Does someone has a clue how I could implement this? Or do you have a better idea how to create my registration?
Glad for all your tips and tricks :)
I could fix it. I created a new file named "patient.module.js" and there I could set the states. My code is the following:
export const patient = {
namespaced: true,
state: {
email: null,
password: null,
location: [],
specialty: [],
attribute: [],
language: [],
gender: [],
},
actions: {
register({ commit }, patient) {
return new Promise((resolve) => {
commit("setPatientData", patient);
resolve();
});
},
},
mutations: {
setPatientData(state, patient) {
Object.assign(state, patient);
},
},
};
As you can see my user state is null at the beginning but when the user logs in, I need to user id for my action called setFavoriteCrypto
So I can retrieve the specific data that is related to the user connected but since vuex initialize the state every time there's a refresh of the page. the user becomes null
I know there's a package called persist state which is something I could work with.
But I would like to know if there's a different way of managing my user connected without depending on a package?
I am using node.js as my backend for this app.
import Api from '#/services/Api'
import axios from 'axios'
import router from '#/router'
const state = {
localStorageToken: localStorage.getItem('user-token') || null,
token: null,
user: null,
favoriteCrypto: []
}
const mutations = {
setToken(state, token) {
state.localStorageToken = token
state.token = token
},
setUser(state, user) {
state.user = user
},
setFavoritecrypto(state, crypto) {
state.favoriteCrypto = crypto
}
}
const actions = {
setToken({commit}, token) {
commit('setToken', token)
},
setUser({commit}, user) {
commit('setUser', user)
},
setFavoriteCrypto({commit}, token) {
if(state.user) {
return Api().get('getuserfavoritescoins', {
params: {
userId: state.user.id
}
})
.then(response => response.data.coins)
.then(cryptoFav => {
commit('setFavoritecrypto', cryptoFav)
})
}
else{
console.log("there's not user state")
}
},
loginUser({commit}, payload) {
return Api().post('login', payload)
.then(response => {
commit('setUser', response.data.user)
commit('setToken', response.data.token)
localStorage.setItem('user-token', response.data.token)
axios.defaults.headers.common['Authorization'] = response.data.token
router.push('/main').catch(e => {})
})
},
logoutUser({commit, dispatch}) {
localStorage.removeItem('user-token')
commit('setUser', null)
commit('setToken', null)
delete axios.defaults.headers.common['Authorization']
}
}
const getters = {
isAuthenticated: state => !!state.localStorageToken,
}
export default {
namespaced: true,
state,
getters,
actions,
mutations
}
I'm extremely new when it comes to using VueJS and so I am working on a small App that should list out an Authenticated person's Github repositories.
I'm having trouble when it comes to being able to access or even traverse the Array in the Picture below. I keep getting an error of undefinedif I try userRepos. Please see my code below.
I do apologize for the "Wall of Code". But I thought these javascript code snippets are the most pertinent to the issue.
This is the GitHub repo I am using as the boilerplate for this project. GitHub-Electron-Vue-OAuth
const getAxiosClient = (state) => {
return axios.create({
baseURL: state.server.url, // this is "https://api.github.com
headers: {
'Authorization': 'token ' + state.session.access_token
},
responseType: 'json'
})
}
// Mutation
[types.SET_USER_REPOS](state, repos) {
state.session.repos = repos;
},
// State Object
const state = {
server: {
url: 'http://api.github.com'
},
session: {
access_token: window.localStorage.getItem('access_token'),
ready: false,
authenticated: false,
user: {}
}
};
// Actions
export const getRepos = ({
commit,
state
}) => {
return new Promise((resolve, reject) => {
getAxiosClient(state).get('/user/repos').then(response => {
commit(types.SET_USER_REPOS, response.data)
resolve(response.data)
}, err => {
console.log(err)
reject(err)
})
})
}
export const userRepos = (state) => {
console.log(state.session.repos)
return state.session.repos;
}
<template lang="jade">
.home
span Hello {{ username }}
span {{ userRepos }}
</template>
<script>
export default {
name: 'home',
computed: {
username() {
return this.$store.getters.username;
},
userRepos() {
return this.$store.getters.userRepos;
}
},
// TODO: Push this in router
beforeRouteEnter(to, from, next) {
next(vm => {
if (!vm.$store.getters.isAuthenticated) {
vm.$router.push({
name: 'login'
});
} else {
next();
}
});
}
}
</script>
I have a React app with the following shallow database model, hooked up to Firebase:
{
"users": {
"userid1": {
"Full name": "Patrick Bateman",
},
},
"posts": {
"userid1": {
"post-1": {
text: "Lorem ipsum",
...
},
"post-2": {
text: "Cats sure are swell",
...
},
},
"userid2": {
...
}
}
}
and in React, I'm using the re-base library's syncState() to fetch initial content and keep the local state and firebase in sync.
In the re-base docs and examples, they use syncState() in componentDidMount. This makes sense, but I don't want to sync all the firebase posts; only those belonging to the user, so my instinct was to do something like this:
componentDidMount() {
this.refs = base.syncState(`posts/${this.state.uid}`, {
context: this,
state: 'posts',
});
}
The problem here is that this.state.uid is null at this stage in the lifecycle.
My question is this: how do I access the uid when I call syncState?
Here is the rest of my code for reference, show auth too:
init() {
// I need the uid here!!!!!! 😫
console.log(this.state.uid); // null
this.refs = base.syncState(`posts/${this.state.uid}`, {
context: this,
state: 'posts',
});
}
componentDidMount() {
this.unsubscribe = firebase.auth().onAuthStateChanged((user) => {
if (user) {
window.localStorage.setItem(storageKey, user.uid);
this.setState({
uid: user.uid,
user
});
} else {
window.localStorage.removeItem(storageKey);
this.setState({
uid: null,
user: null,
posts: null,
});
}
});
// re-base firebase sync
this.init();
}
componentWillUnmount() {
base.removeBinding(this.ref);
this.unsubscribe();
}
authenticate = (provider) => {
if (provider === 'twitter') {
provider = new firebase.auth.TwitterAuthProvider();
} else if (provider === 'google') {
provider = new firebase.auth.GoogleAuthProvider();
provider.addScope('https://www.googleapis.com/auth/plus.login');
}
firebase.auth().signInWithPopup(provider).then((authData) => {
// get the of the firebase.User instance
const user = authData.user;
// Set local storage to preserve login
window.localStorage.setItem(storageKey, user.uid);
// Set the state of the current user
this.setState({
uid: user.uid,
user,
});
}).catch(function(error) {
console.log(error);
});
};
With the above code, my app creates local state correctly:
State
posts: {
post-1: {
...
}
}
but then on firebase, predicately adds them with a null user, since the uid is not available.
database: {
posts: {
null: {
post-1: {
...
}
}
}
}
You can just call this.init() after the state sets. this.setState has a second argument that is a callback. This way you can be sure that the uid will not be null.
Example
this.setState({
uid: user.uid,
user
}, () => {
this.init();
});
I am trying to render different UIs depending on whether a user is a retailer or not. I think I have mostly everything correct, but when the app initializes, I want to check whether the user is a retailer or not (This dispatches the checkAuth action).
I try running the following to get the value of the isRetailer property from Firebase.
firebase.database().ref('/users/' + user.uid + '/isRetailer').once('value').then(snapshot => snapshot.val()
Then I dispatch some actions based on the result. For some reason, the isRetailer part of my Vuex state is not updating from false even when the users isRetailer property is true.
I'm not really sure why but I'm guessing it has something to do w/ my firebase reference. My full code is below. Thanks!
import firebase from 'firebase'
const authentication = {
state: {
isAuthed: false,
authId: '',
isRetailer: false
},
mutations: {
authUser (state, user) {
state.isAuthed = true;
state.authId = user.uid;
},
notAuthed (state) {
state.isAuthed = false;
state.authId = '';
state.isRetailer = false
},
isRetailer (state) {
state.isRetailer = true
},
isNotRetailer (state) {
state.isRetailer = false
}
},
actions: {
checkUser (context, user) {
if (!user.uid) {
// Do nothing.
} else if (firebase.database().ref('/users/' + user.uid + '/isRetailer').once('value').then(snapshot => snapshot.val()) === true) {
context.commit('authUser', user);
context.commit('isRetailer');
} else {
context.commit('authUser', user);
context.commit('isNotRetailer');
};
},
signOut (context) {
context.commit('notAuthed')
},
setRetailer (context, payload) {
// Set retailer info in Firebase.
var uid = payload.user.uid;
firebase.database().ref('/users/' + uid).set({
name: payload.name,
email: payload.email,
location: payload.retailerLocation,
isRetailer: payload.isRetailer
});
},
setNewUser (context, payload) {
// Sets a user in firebase w/ a isRetailer value of false.
var uid = payload.user.uid;
firebase.database().ref('/users/' + uid).set({
name: payload.name,
email: payload.email,
isRetailer: payload.isRetailer
});
}
},
getters: {}
};
export default authentication;
This might be happening because you have given same name to mutation and state variable: isRetailer, I don't have any reference right now, but this might be the case for mutation not triggering, You can try once by setting your mutation by different name such as:
mutations: {
...
...
setIsRetailer (state) {
state.isRetailer = true
},
isNotRetailer (state) {
state.isRetailer = false
}
},
and use this in actions:
actions: {
checkUser (context, user) {
...
...
context.commit('authUser', user);
context.commit('setIsRetailer');
}