I'm working on this problem for a few days and I don't know how to solve it.
This is my nuxt login page and I use the new Firebase 9 auth pack to authenticate a user.
I call the signInWithEmailAndPassword method to authenticate.
When I try it with the correct credentials I never get into the first then() of the Promise:
.then((userCredential) => {
alert(userCredential)
this.$store.commit('setUser', userCredential.user)
})
But when I type in the incorrect credentials, I always get the correct error (in the catch) and the second then() is always executed.
I don't understand why I can't log in.
Can anyone help me?
Sorry for the bad English.
My login page: (pages/index.vue)
<template>
<v-container fluid fill-height>
<v-layout align-center justify-center>
<v-flex xs12 sm8 md4>
<v-card class="elevation-12">
<v-toolbar dark color="primary">
<v-toolbar-title>Anmelden</v-toolbar-title>
</v-toolbar>
<v-card-text>
<v-form
id="login-form"
ref="form"
v-model="valid"
lazy-validation
#submit.prevent="emailLogin()"
>
<v-text-field
v-model="formData.email"
:rules="emailRules"
name="email"
label="E-Mail"
counter
required
/>
<v-text-field
v-model="formData.password"
:append-icon="show ? 'mdi-eye' : 'mdi-eye-off'"
:rules="passwordRules"
:type="show ? 'text' : 'password'"
name="password"
label="Passwort"
counter
required
#click:append="show = !show"
/>
</v-form>
</v-card-text>
<v-snackbar
v-model="snackbar"
:timeout="timeout"
>
{{ text }}
<template #action="{ attrs }">
<v-btn
color="yellow accent-2"
text
v-bind="attrs"
#click="snackbar = false"
>
Schließen
</v-btn>
</template>
</v-snackbar>
<v-card-actions>
<v-spacer />
<v-btn
type="submit"
form="login-form"
:disabled="!valid"
block
color="primary"
class="mr-4"
>
Login
</v-btn>
</v-card-actions>
</v-card>
</v-flex>
</v-layout>
</v-container>
</template>
<script>
import { auth, signInWithEmailAndPassword } from '#/plugins/firebase'
export default {
data: () => ({
show: false,
valid: true,
snackbar: '',
timeout: 10000,
text: '',
formData: {
email: '',
password: ''
},
emailRules: [
v => !!v || 'E-Mail ist verpflichtend',
v => /.+#.+\..+/.test(v) || 'Keine gültige E-Mail-Adresse'
],
passwordRules: [
v => !!v || 'Passwort ist verpflichtend'
]
}),
methods: {
emailLogin () {
signInWithEmailAndPassword(auth, this.formData.email, this.formData.password)
.then((userCredential) => {
alert(userCredential)
this.$store.commit('setUser', userCredential.user)
})
.catch((error) => {
switch (error.code) {
case 'auth/invalid-email':
this.text = 'Die E-Mail-Adresse ist falsch'
break
case 'auth/user-disabled':
this.text = 'Der User ist deaktiviert'
break
case 'auth/user-not-found':
this.text = 'Kein Account gefunden'
break
case 'auth/wrong-password':
this.text = 'Das Passwort ist falsch'
break
default:
this.text = 'Es ist ein Fehler aufgetreten: ' + error.message
break
}
this.snackbar = true
}).then(() => {
this.formData.email = ''
this.formData.password = ''
this.$refs.form.resetValidation()
this.$router.push('/post')
})
}
}
}
</script>
My firebase setup file: (plugins/firbase.js) --> is registered in nuxt.config.js
import { initializeApp } from 'firebase/app'
import { getFirestore } from 'firebase/firestore'
import { getStorage } from 'firebase/storage'
import { getAuth, signInWithEmailAndPassword, signOut, onAuthStateChanged } from 'firebase/auth'
const firebaseConfig = {
apiKey: 'key',
authDomain: 'domain',
projectId: 'project',
storageBucket: 'bucket',
messagingSenderId: 'message',
appId: 'app',
measurementId: 'measure'
}
const app = initializeApp(firebaseConfig)
const auth = getAuth(app)
const fire = getFirestore(app)
const storage = getStorage(app)
export { auth, fire, storage, signInWithEmailAndPassword, signOut, onAuthStateChanged }
Related
this is a related question which I've asked before:
Get document data from Firestore and show the data into each of the form input field using Nuxt & Vuetify
I want the data that I've submitted to display on the v-text-field input.
As you can see from the image, I can submit my form and I can get the data accordingly.
Name: siradley_ <-- this come from my firestore
but I want it to display inside the v-text-field input, not outside the input field.
Currently, I still not know how to do it.
Any help on how to do it?
<template>
<div>
<v-container>
<v-layout>
<v-flex>
<v-card>
<v-card-text>
<v-form>
<v-layout>
<v-row>
<v-col cols="12" sm="6" md="6" v-for="(test, id) in Test">
<v-text-field
v-model="editedItem.name">{{ test.name }}</v-text-field>
<p>Name: {{ test.name }}</p>
</v-col>
<v-col cols="12" sm="6" md="6">
<v-btn #click="test">Test</v-btn>
</v-col>
</v-row>
</v-layout>
</v-form>
</v-card-text>
</v-card>
</v-flex>
</v-layout>
</v-container>
</div>
</template>
my script
<script>
import firebase from "firebase/app";
import firestore from "#/plugins/firebasetest";
export default {
middleware: "authentication",
layout: 'dashboard',
data: () => ({
Test: [
{
name: '',
}
],
editedItem: {
name: '',
}
}),
created() {
this.readTest();
},
methods: {
readTest() {
this.Test = [];
firestore
.collection('test')
.doc(firebase.auth().currentUser.uid)
.get()
.then((doc) => {
this.Test.push({ ...doc.data(), id: doc.id });
console.log({ ...doc.data(), id: doc.id });
})
},
test() {
var data = {
name: this.editedItem.name,
}
firestore
.collection('test')
.doc(firebase.auth().currentUser.uid)
.set(data)
.then((doc) => {
window.location.reload();
console.log({ ...doc.data, id: doc.id })
})
},
},
}
</script>
you have to update the value editedItem.name in your data object after getting the value from the server.
you have two way data binding set on the v-text-field (i.e. v-model), so you just need to use v-text-field like this:
<v-text-field v-model="editedItem.name" ></v-text-field>
and then in the code after you get the data from the server update the mentioned field in the data:
async getDataFromServerExample() {
const data = await getData();
this.editedItem.name = data.properFieldFromServerResponse;
}
then everything should work fine.
Finally can solve it hehe.
Referring to this Unable to display data in Vue.js form after pulling from Cloud Firestore , I now can display my input data inside my v-text-field.
Here's how I do it:
<v-form>
<v-layout>
<v-row :items="Test">
<v-col cols="12" sm="6" md="6">
<v-text-field
v-model="editedItem.name"></v-text-field>
</v-col>
<v-col cols="12" sm="6" md="6">
<v-btn #click="test">Test</v-btn>
</v-col>
</v-row>
</v-layout>
</v-form>
<script>
import firebase from "firebase/app";
import firestore from "#/plugins/firebasetest";
export default {
middleware: "authentication",
layout: 'dashboard',
data: () => ({
editedItem: {
name: '',
}
}),
created() {
this.readTest();
},
methods: {
readTest() {
let _this = this;
firestore
.collection('test')
.doc(firebase.auth().currentUser.uid)
.get()
.then((doc) => {
if (doc.exists) {
console.log("Document data:", doc.data())
_this.editedItem.name = doc.data().name
} else {
console.log("No Document!");
}
}).catch((error) => {
console.log("Error :(");
})
},
},
}
</script>
I added let _this = this; and _this.editedItem.name = doc.data().name and it works.
My setUser
setUser(state, payload) {
state.user = {...payload}
}
my payload in setUser for random data is
user ===
payload{"uid":"pQOQL9AqMHNsozDE2EFGbMfHZlt1","refreshToken":"AEu4IL3c4doh1ON1ywqNEIXPjijktxAyQsYusC5twuvM61bHK6PpLHENyqKRKGCvNPR5IxBRC7JLQhkjv1qqiVUPdatRVM2Q8VdBCnvxyKkBjOEt_kM6bHCiJI6cdESdmFWZf2B7EjG9MwUJ7l8ASOpdbQLLVs9NtuW94dpNg1dkQShtUXB-sVCafvgtSnluGyZSWGhkt8uJ","photoURL":null,"displayName":null,"email":"yyy#test.com"}
My signUserUp
signUserUp(context, payload) {
//name , email , and password are in payload
context.commit("setLoading", true);
context.commit("clearError");
context.commit("setUserAvatar")
firebase
.auth()
.createUserWithEmailAndPassword(payload.email, payload.password)
.then((data) => {
data.user.updateProfile({
displayName: payload.name ,
photoURL: 'https://avataaars.io/?avatarStyle=Circle&topType=ShortHairDreads01&accessoriesType=Prescription01&hairColor=BlondeGolden&facialHairType=BeardMedium&facialHairColor=BrownDark&clotheType=Hoodie&clotheColor=Gray01&eyeType=Squint&eyebrowType=AngryNatural&mouthType=Sad&skinColor=Light'
})
return data
})
.then((data) => {
context.commit("setLoading", false);
db.collection("profilesInfo")
.add({
id: data.user.uid,
registeredMeetups: []
})
.then(function() {
context.commit("setProfilesInfo",
{
id: data.user.uid,
registeredMeetups: []
}
)
console.log("Document successfully written!");
})
.catch(function(error) {
console.error("Error writing document: ", error);
});
context.commit("setUser", {
name: payload.name ,
id: data.user.uid,
photoURL: 'https://avataaars.io/?avatarStyle=Circle&topType=ShortHairDreads01&accessoriesType=Prescription01&hairColor=BlondeGolden&facialHairType=BeardMedium&facialHairColor=BrownDark&clotheType=Hoodie&clotheColor=Gray01&eyeType=Squint&eyebrowType=AngryNatural&mouthType=Sad&skinColor=Light',
email: data.user.email
})
router.push("/");
})
.catch(function(error) {
// Handle Errors here.
context.commit("setLoading", false);
context.commit("setError", error);
});
},
In signUserUp
an user will be created and upon creation value of photoURL and displayName get updated by updateProfile
and after that db is connected again in order to create profilesinfo related to the user which is about showing what meetup groups the user is registered already
It works when in my setUser, I set the value of payload inside setUser and photoURL and displayName will be populated right and I can use it in my profile vue component
I debugged everything inside the console and I cannot understand why this part does not pass photoURL and displayName right
context.commit("setUser", {
name: payload.name ,
id: data.user.uid,
photoURL: 'https://avataaars.io/?avatarStyle=Circle&topType=ShortHairDreads01&accessoriesType=Prescription01&hairColor=BlondeGolden&facialHairType=BeardMedium&facialHairColor=BrownDark&clotheType=Hoodie&clotheColor=Gray01&eyeType=Squint&eyebrowType=AngryNatural&mouthType=Sad&skinColor=Light',
email: data.user.email
})
Note: I cleared my storage very often
or In second thought, can my issue is because of using persistent data?
const vuexLocalStorage = new VuexPersist({
key: 'devmeetup-it', // The key to store the state on in the storage provider.
storage: window.localStorage, // or window.sessionStorage or localForage
// Function that passes the state and returns the state with only the objects you want to store.
// reducer: state => ({
// keepLoadedMeetups : store.getters.loadedMeetups,
// keepUser: store.getters.user,
// keepProfilesInfo: state.profilesInfo
// // getRidOfThisModule: state.getRidOfThisModule (No one likes it.)
// })
// Function that passes a mutation and lets you decide if it should update the state in localStorage.
// filter: mutation => (true)
})
Note: after reloading and visiting other pages and come back to profile page, the photo is shown I guess the info became available then?
My Profile.vue
<template >
<div>
<v-card
class="mx-auto"
max-width="434"
tile
>
<v-img
height="100%"
src="https://cdn.vuetifyjs.com/images/cards/server-room.jpg"
>
<v-row
align="end"
class="fill-height"
>
<v-col
align-self="start"
class="pa-0"
cols="12"
>
<v-avatar
class="profile"
size="164"
tile
>
<img :src="imgUrl" alt="">
</v-avatar>
</v-col>
<v-col class="py-0">
<v-list-item
color="rgba(0, 0, 0, .4)"
dark
>
<v-list-item-content>
<v-list-item-title class="title">Name: {{owner_name}}</v-list-item-title>
<v-list-item-subtitle>Email: {{user_info.email}}</v-list-item-subtitle>
<template v-if="meetups.length> 0 ">
<v-list-item-subtitle>Meetup organizer :</v-list-item-subtitle>
<v-card color="rgba(255, 0, 0, 0.5)">
<ol start="1" v-for="(meetup,i) in meetups" v-bind:key="i">
<span >{{i+1}}. {{meetup.title}}</span>
</ol>
</v-card>
</template>
<template>
<div v-if="registeredMeetups.length> 0 ">
<v-list-item-subtitle>Meetup Registred :</v-list-item-subtitle>
<v-card color="rgba(255, 0, 0, 0.5)">
<ol start="1" v-for="(meetup,i) in registeredMeetups" v-bind:key="i">
<span >{{i+1}}. {{meetup.title}}</span>
</ol>
</v-card>
</div>
</template>
</v-list-item-content>
</v-list-item>
</v-col>
</v-row>
</v-img>
</v-card>
<!--<h3>orginzer meetups: {{this.meetups}}</h3>
<h3>registered meetups: {{this.registeredMeetups}}</h3>
<h3>All the meetups: {{this.$store.getters.loadedMeetups}} </h3>
<div style="word-wrap: break-word"> {{imgUrl}} </div>-->
</div>
</template>
<script>
import {mapState} from 'vuex'
export default {
data(){
return {
imgUrl: this.$store.state.user.photoURL
}
},
created(){
// this.$store.subscribe((mutation, state) => {
// if (mutation.type === "setUserAvatar") {
// //debugger; // eslint-disable-line no-debugger
// this.imgUrl = state.user.photoURL
// }
// });
},
computed: {
...mapState({
owner_name: state => state.user.displayName,
user_info: state => state.user
}),
registeredMeetups(){
let rm= this.$store.getters.currentUserProfileInfo.registeredMeetups
let allm = this.$store.getters.loadedMeetups
let meetupsInfo = []
let i , j
console.log("rm and all meetups are " + JSON.stringify(allm))
for (i = 0; i < rm.length; i++) {
console.log("rm=" + rm[i].toString() )
for ( j = 0 ; j < allm.length; j++){
console.log("lm= " + JSON.stringify(allm[j]))
if(allm[j].id == rm[i].toString())
meetupsInfo.push(allm[j])
}
}
console.log("meetupsInfo " + JSON.stringify(this.$store.state.photoURL))
return meetupsInfo
},
meetups(){
return this.$store.getters.loadedMeetups
.filter( meetup => meetup.creatorId === this.$store.getters.user.uid )
},
profilesInfo(){
// let currentUserProfile = this.$store.state.profilesInfo
// .find( userProfile =>
// userProfile.id === this.$store.getters.user.uid )
return this.$store.getters.currentUserProfileInfo
}
}
}
</script>
or May be, using then clause inside another the clause will have different effect ?
please take a look at my signUserUp then clauses.
my github repo
github.com/KickButtowski80/devmeetup/tree/setting-avataaars
please if more info is needed let me know
thank you
I see there is some different parameter passed in setUser()
In your signUserUp(context, payload):
...
context.commit("setUser", {
name: payload.name ,
id: data.user.uid,
photoURL: 'https://avataaars.io/?avatarStyle=Circle&topType=ShortHairDreads01&accessoriesType=Prescription01&hairColor=BlondeGolden&facialHairType=BeardMedium&facialHairColor=BrownDark&clotheType=Hoodie&clotheColor=Gray01&eyeType=Squint&eyebrowType=AngryNatural&mouthType=Sad&skinColor=Light',
email: data.user.email
});
router.push("/");
...
You also said :
It works when in my setUser, I set the value of payload inside setUser
and photoURL and displayName will be populated right and I can use it
in my profile vue component
Does it mean you put it in /store/index.js :
setUser(state, payload) {
const {uid, refreshToken, photoURL, displayName, email} = payload;
console.log('user === payload' + JSON.stringify(payload))
console.log('payload detail info ' + payload.uid + " " + payload.refreshToken
+ " " + payload.photoURL + " " + payload.displayName + " " + payload.email )
// payload = {
// displayName:"test7",
// email:"test7#test.com",
// photoURL:"https://avataaars.io/?avatarStyle=Circle&topType=ShortHairDreads01&accessoriesType=Prescription01&hairColor=BlondeGolden&facialHairType=BeardMedium&facialHairColor=BrownDark&clotheType=Hoodie&clotheColor=Gray01&eyeType=Squint&eyebrowType=AngryNatural&mouthType=Sad&skinColor=Light",
// refreshToken:"AEu4IL0tC9-fuEO-KZNwq953YDo2V7FBpjqB62FT6nXJ5d3r5u3Fzk1RYDzbjkO885rz0LrLyvIjHKHIDemiZsVPeio5XPXK5ntuRyFtLYcu-QOV4xnYYMn18mFxjo6P_TeqrnGIBuwpoto0ceTPxNfYFmedNyuxbNIU6MUVRp5WvnI7OWxVO5404RHIsnLrBsABoigDZgxs",
// uid:"XAhAqlBbs5VZCredSDqdWqKze6C3",
// }
state.user = {...{uid, refreshToken, photoURL, displayName, email}}
So, if you uncomment the line it works ?
Try to pass all the params used with the same key:
...
context.commit("setUser", {
uid: data.user.uid, // id => uid,
displayName: payload.name , // name=> displayName
refreshToken: 'your-token',
photoURL: 'https://avataaars.io/?avatarStyle=Circle&topType=ShortHairDreads01&accessoriesType=Prescription01&hairColor=BlondeGolden&facialHairType=BeardMedium&facialHairColor=BrownDark&clotheType=Hoodie&clotheColor=Gray01&eyeType=Squint&eyebrowType=AngryNatural&mouthType=Sad&skinColor=Light',
email: data.user.email
});
router.push("/");
...
Does it work ?
I'm following a course here:
https://thinkster.io/tutorials/nuxt-js-project/adding-authentication
I am working on adding authentication to my app and have login/logout buttons that partially work with firebase authentication. I can log in fine, but the issue is that when I'm logged in, the action in my Vuex store doesn't seem to run, therefore leaving the user logged in and the state not updating to display the logout button.
default.vue
<template>
<v-app>
<v-navigation-drawer
v-model="drawer"
:mini-variant="miniVariant"
:clipped="clipped"
fixed
app
>
<v-list>
<v-list-item
v-for="(item, i) in items"
:key="i"
:to="item.to"
router
exact
>
<v-list-item-action>
<v-icon>{{ item.icon }}</v-icon>
</v-list-item-action>
<v-list-item-content>
<v-list-item-title v-text="item.title" />
</v-list-item-content>
</v-list-item>
<button v-if="!mySession" #click="login">Login</button>
<button v-else #click="logout">Logout</button>
</v-list>
</v-navigation-drawer>
<!-- <v-toolbar fixed app :clipped-left="clipped">
<v-toolbar-side-icon #click="drawer = !drawer"></v-toolbar-side-icon>
<v-tool-bar-title v-text="title"></v-tool-bar-title>
<v-spacer></v-spacer>
<v-toolbar-items>
<v-btn #click="login">Login</v-btn>
<v-btn #click="logout">Logout</v-btn>
</v-toolbar-items>
</v-toolbar> -->
<v-app-bar
:clipped-left="clipped"
fixed
app
>
<v-app-bar-nav-icon #click.stop="drawer = !drawer" />
<v-btn
icon
#click.stop="clipped = !clipped"
>
<v-icon>mdi-application</v-icon>
</v-btn>
<v-btn
icon
#click.stop="fixed = !fixed"
>
<v-icon>mdi-minus</v-icon>
</v-btn>
<v-toolbar-title v-text="title" />
<v-spacer />
</v-app-bar>
<v-content>
<v-container>
<nuxt />
</v-container>
</v-content>
<v-navigation-drawer
v-model="rightDrawer"
:right="right"
temporary
fixed
>
<v-list>
<v-list-item #click.native="right = !right">
<v-list-item-action>
<v-icon light>
mdi-repeat
</v-icon>
</v-list-item-action>
<v-list-item-title>Switch drawer (click me)</v-list-item-title>
</v-list-item>
</v-list>
</v-navigation-drawer>
<v-footer
:fixed="fixed"
app
>
<span>© 2019</span>
</v-footer>
</v-app>
</template>
<script>
import {db} from '#/plugins/firebase'
import firebase from 'firebase/app'
import 'firebase/auth'
export default {
created() {
this.$store.dispatch('setSession');
},
data () {
return {
clipped: false,
drawer: false,
fixed: false,
items: [
{
icon: 'mdi-apps',
title: 'Welcome',
to: '/'
},
{
icon: 'cart',
title: 'Checkout',
to: '/checkout'
}
],
miniVariant: false,
right: true,
rightDrawer: false,
title: 'Vuetify.js'
}
},
methods: {
login() {
console.log('login');
let provider = new firebase.auth.GoogleAuthProvider();
firebase.auth()
.signInWithPopup(provider)
.then(function(result) {
console.log('signed in');
})
.catch(function(error) {
console.log(error);
})
},
logout() {
console.log('logout');
firebase.auth()
.signOut()
.then(() => {
console.log('sign out')
}).catch((error) => {
console.log(error)
})
}
},
computed: {
mySession() {
return this.$store.getters.session;
}
}
}
</script>
store/index.js
import Vuex from 'vuex'
import firebase from 'firebase/app'
import 'firebase/auth'
const createStore = () => {
return new Vuex.Store({
state: {
session: false
},
mutations: {
SET_SESSION(state, session) {
state.session = session;
}
},
getters: {
session: state => state.session
},
actions: {
setSession({commit}) {
firebase.auth().onAuthStateChanged(user => {
console.log(user);
console.log('change');
commit('SET_SESSION', user || false);
})
}
}
})
}
export default createStore
in console I am getting an error message that says:
"[vuex] unknown action type: setSession"
To reiterate, I can login using Google oauth, but when logged in, the state does not change and the logout button does not appear.
Thanks for the help!
Update:
Well now I'm extra confused. I did push updates 15 mins ago but for some reason my store/index.js file is outdated and isn't updating/saving? I have no idea what I'm doing wrong.
When looking at my store/index.js file on Github, it shows the default template:
https://github.com/SIeep/US-kratom/blob/master/US-Kratom/store/index.js
But what I have, and what was just copied from the course I'm taking is:
import Vuex from 'vuex';
import firebase from 'firebase/app';
import 'firebase/auth';
const createStore = () => {
return new Vuex.Store({
state: {
session: false,
products: []
},
mutations: {
SET_SESSION(state, session) {
state.session = session;
},
SET_PRODUCT(state, product) {
state.products = product;
}
},
getters: {
session: state => state.session,
products: state => state.products
},
actions: {
setSession({ commit }) {
firebase.auth().onAuthStateChanged(user => {
commit('SET_SESSION', user || false);
});
},
setProduct({ commit }, products) {
commit('SET_PRODUCT', products);
}
}
});
};
export default createStore;
I am saving the file and everything but it's not updating on Github which is obviously the issue with my app as well.
Erik from Thinkster.io ended up fixing the code for me. Update is here:
[https://github.com/SIeep/US-kratom/commit/bd55deacadfc065edc7df9c1365ae832a32b9b43][1]
I'm a beginner in writing vue js. I want to edit an exiting date in the app am working on based on a tutorial video am watching and the new date should be updated both in the app and Firebase when the SAVE button is clicked.
Am getting an error this which i think is not allowing the v-dialog to show but when i change the v-model in the v-date-picker to date which is included in my data as
props: ['meetup'],
data () {
return {
editDialog: false,
editableDate: null,
date: new Date().toISOString().substr(0,10)
}
}
the v-dialog works with no error but i get this error when the v-model is changed from date to editableDate:
vue.runtime.esm.js?ff9b:587 [Vue warn]: Invalid prop: type check failed for prop "value". Expected Array, String, got Date.
vue.runtime.esm.js?ff9b:587 [Vue warn]: Error in data(): "TypeError: dateString.split is not a function"
vue.runtime.esm.js?ff9b:1737 TypeError: dateString.split is not a function
vue.runtime.esm.js?ff9b:587 [Vue warn]: Error in nextTick: "TypeError: Cannot set property 'isDark' of undefined"
TypeError: Cannot set property 'isDark' of undefined
<template>
<v-dialog width="350px" persistent v-model="editDialog" ref="dialog" lazy full-width>
<v-btn accent slot="activator">
Edit Date
</v-btn>
<v-card>
<v-container>
<v-layout row wrap>
<v-flex xs12>
<v-card-title>Edit Meetup Date</v-card-title>
</v-flex>
</v-layout>
<v-divider></v-divider>
<v-layout row wrap>
<v-flex xs12>
<v-date-picker v-model="editableDate" style="width: 100%" actions>
<v-spacer></v-spacer>
<template slot-scope="{save, cancel}">
<v-btn
class="blue--text darken-1"
flat
#click.native="editDialog = false">
Close
</v-btn>
<v-btn
class="blue--text darken-1"
flat
#click.native="onSaveChanges">
Save
</v-btn>
</template>
</v-date-picker>
</v-flex>
</v-layout>
</v-container>
</v-card>
</v-dialog>
</template>
scripts
<script>
export default {
props: ['meetup'],
data () {
return {
editDialog: false,
editableDate: null
}
},
methods: {
onSaveChanges () {
const newDate = new Date(this.meetup.date)
const newDay = new Date(this.editableDate).getUTCDate()
const newMonth = new Date(this.editableDate).getUTCMonth()
const newYear = new Date(this.editableDate).getUTCFullYear()
newDate.setUTCDate(newDay)
newDate.setUTCMonth(newMonth)
newDate.setUTCFullYear(newYear)
this.$store.dispatch('updateMeetupData', {
id: this.meetup.id,
date: newDate
})
}
},
created () {
this.editableDate = new Date(this.meetup.date)
}
}
</script>
Have tried all i could but to no avail please i need help
This is my store
updateMeetupData ({commit}, payload) {
commit('setLoading', true)
const updateObj = {}
if (payload.title) {
updateObj.title = payload.title
}
if (payload.description) {
updateObj.description = payload.description
}
if (payload.date) {
updateObj.date = payload.date
}
firebase.database().ref('meetups').child(payload.id).update(updateObj)
.then(() => {
commit('setLoading', false)
commit('updateMeetup', payload)
})
.catch(error => {
console.log(error)
commit('setLoading', false)
})
},
I've a simple vuejs app, connected to firebase, the v-for in the child component was working perfectly until I implemented authentication with firebase and the vue router.
Now its broken :(
Authentication happens fine, but the items from the query are not being there anymore (undefined).
Firebase credentials are good and the database herself has data on the selected path.
this is main.js
import 'onsenui';
import Vue from 'vue';
import VueOnsen from 'vue-onsenui';
import VueFire from 'vuefire';
import VueRouter from 'vue-router'
import firebaseui from 'firebaseui';
import router from './router'
import {connection} from './firebaseconfig';
require('onsenui/css-components-src/src/onsen-css-components.css');
require('onsenui/css/onsenui.css');
require('firebaseui/dist/firebaseui.css');
import App from './App.vue';
Vue.use(VueOnsen);
Vue.use(VueFire);
Vue.use(VueRouter);
var app = new Vue({
router,
created() {
connection.auth().onAuthStateChanged((user) => {
if(user) {
this.$router.push('/home')
} else {
this.$router.push('/auth')
}
});
} ,
el: '#app',
template: '<app></app>',
components:{
App
} ,
render: h => h(App)
});
App.vue
<template>
<router-view></router-view>
</template>
<script>
import auth from './components/auth'
import dashboard from './components/dashboard'
import home from './components/homePage'
import stores from './components/storesPage'
import social from './components/socialPage'
import settings from './components/settingsPage'
export default {
data() {
return {
currentPage: 'auth',
// pages: ['home', 'stores', 'settings' , 'social'],
pages: {
'dashboard' :
{ 'name' : 'dashboard' , 'icon' : 'md-view-dashboard' } ,
'home' :
{ 'name' : 'home' , 'icon' : 'md-view-home' } ,
'Stores' :
{ 'name' : 'stores' , 'icon' : 'md-store' } ,
'Social' :
{ 'name' : 'social' , 'icon' : 'md-share' } ,
'account' :
{ 'name' : 'account' , 'icon' : 'md-account-o' } ,
'auth' :
{ 'name' : 'auth' , 'icon' : 'md-settings' } ,
},
openSide: false
};
},
components: {
auth,
dashboard,
home,
stores,
settings ,
social
}
}
</script>
Fire base config :
import firebase from 'firebase';
const config = {
apiKey: "xxxxxxxxxx",
authDomain: "xxx",
databaseURL: "xxx",
projectId: "yyyyy",
storageBucket: "yyyyyyy",
messagingSenderId: "yyyyy"
};
export const FireBconfig = config;
export const connection = firebase.initializeApp(config);
export const db = connection.database();
auth.vue
<template lang="html">
<div id="firebaseui-auth-container">
</div>
</template>
<script>
import firebase from 'firebase';
import firebaseui from 'firebaseui'
import {FireBconfig} from '../firebaseconfig';
export default {
name: 'auth',
mounted() {
var uiConfig = {
signInSuccessUrl: '/success',
signInOptions: [
firebase.auth.GoogleAuthProvider.PROVIDER_ID,
firebase.auth.EmailAuthProvider.PROVIDER_ID
]
};
var ui = new firebaseui.auth.AuthUI(firebase.auth());
ui.start('#firebaseui-auth-container', uiConfig);
},
}
</script>
and finally the child component displaying on successful auth and pulling data from the firebase path
<template>
<v-ons-page style="background-color:grey">
<custom-toolbar class="topbarback" :title="'Home'" :action="toggleMenu">
</custom-toolbar>
<v-ons-pull-hook :action="loadItem" #changestate="state = $event.state">
<span v-show="state === 'initial'"> Pull to refresh </span>
<span v-show="state === 'preaction'"> Release </span>
<span v-show="state === 'action'"> <v-ons-progress-bar indeterminate></v-ons-progress-bar> </span>
</v-ons-pull-hook>
<v-ons-row >
<v-ons-col v-bind:key="item" v-for="item in items" width="33%">
<div style="padding:5px;margin: 0px;border:solid 2px #E4E4E4;height:240px;vertical-align:middle;display:table-cell;background-color:#FFF;position: relative;">
<div style="text-align:center">
<ons-input #change="checkboxclick" :input-id="item.ItemID" v-model="selected" style=" position: absolute; top: 10px; right: 10px;" type="checkbox" ></ons-input>
<label :for="item.ItemID">
<span class="price">{{item.CurrentPriceAmount}} €</span>
<span class="watchers">10</span>
<img tappable style="width:85%;max-height:85%" class="item-thum" v-bind:src="item. PictureDetailsGalleryURL" />
</label>
</div>
<div class="item-title"> <span style="font-size:9px;background-color:#FFF">{{item.title}}</ span><br /><br /></div>
</div>
</v-ons-col>
</v-ons-row>
<v-ons-speed-dial position="bottom right" direction="up"
:visible="spdVisible"
:open.sync="spdOpen"
>
<v-ons-fab :style="spdStyle">
<v-ons-icon style="font-size:8px" icon="md-format-valign-top"><span style=" font-size:12px;font-family: 'Open Sans', sans-serif;">{{counter}}</span></v-ons-icon>
</v-ons-fab>
<v-ons-speed-dial-item v-for="(icon, name) in shareItems"
:style="spdStyle"
#click="$ons.notification.confirm(`Share on ${name}?`)"
>
<v-ons-icon :icon="icon"></v-ons-icon>
</v-ons-speed-dial-item>
</v-ons-speed-dial>
</v-ons-page>
</template>
<script>
import customToolbar from './toolbarHome'
import {db} from '../firebaseconfig';
export default {
data :
function() {
return {
spdVisible: false,
spdOpen: false,
spdStyle: {
backgroundColor: this.$ons.platform.isIOS() ? '#4282cc' : null
} ,
items : [1,2,3] ,
counter : 0 ,
selectedItems : [] ,
state: 'initial',
selected : [],
shareItems: {
'With Relist': 'md-swap-alt' ,
'Facebook': 'md-arrow-split',
}
}
},
firebase: {
items : {
source: db.ref('users/buisine/stores/ebay/red/items')
}
},
props: ['toggleMenu' , 'itemsRef'],
components: { customToolbar } ,
methods: {
checkboxclick(event) {
if(event.target.checked===true)
{
this.counter++;
this.selectedItems.push(event.target.id);
}
else
{
this.selectedItems.splice( this.selectedItems.indexOf(event.target.id) , 1);
this.counter--;
}
},
loadItem(done) {
setTimeout(() => {
this.items = [...this.items, this.items.length + 1];
done();
}, 1500);
},
}
}
</script>
Tried different code on the firebase object that should return the data, nothing worked.
Well, tried on clean blank vuejs project, failed again.
BUT worked again by supressing all Users in the authentication tab in firebase console !!