Vuex photoURL and displayName have been passed null to SetUser - firebase

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 ?

Related

How do you access session.user.id in nextauth?

I am using next-auth version 4.19.2 .
I have a simple component that just displays who they're logged in as:
import { useSession, signIn, signOut } from "next-auth/react"
export default function LoginPlaceholder() {
const { data: session } = useSession();
if(session) {
return <>
Signed in as
userID: {session.user.id} <br/>
name: {session.user.name} <br/>
email: {session.user.email} <br/>
<button onClick={() => signOut()}>Sign out</button>
</>
}
return <>
Not signed in <br/>
<button onClick={() => signIn()}>Sign in</button>
</>
}
My [...nextauth.js] just returns some dummy data:
async authorize(credentials) {
console.log("authorize script running...");
const user = { id: 22, name: 'J Smith', email: 'jsmith#example.com' }
return user;
}
For some reason, my output only displays the name and email, but no id.
Signed in as userID:
name: J Smith
email: jsmith#example.com
I work on a project, where multiple people in an organization could share the same email address (not my idea), so email is not a unique identifier for me. I need the either the ID or the username, as a unique identifier, but I was unsure how to get that.
I also tried passing other data, but the only thing I can get to show up is name and email.
const user = { id: 22, userName: 'jSmith' name: 'J Smith', email: 'jsmith#example.com' }
But again, my components are not getting any values for anything other than name and email.
My question is: How do I modify my code to display the username?
You should use callbacks, something along these lines:
callbacks: {
async jwt({token, user}) {
if (user?.id) {
token.id = user.id
}
if (user?.userName) {
token.userName = user.userName;
}
return token
},
async session({session, token}) {
session.id = token.id;
session.userName = token.userName;
return session;
}
}

firebase auth in nuxt store module mode

Since converting from Vuex classic to module mode, my login function is broken
index.vue login interface
login() {
if (this.$refs.loginForm.validate()) {
const email = this.loginData.email
const password = this.loginData.password
this.$notifier.showMessage({ text: 'Logging in', color: 'primary' })
this.$store.dispatch('user/userLogin', { email, password }).then(
(result) => {
//
},
(error) => {
this.$notifier.showMessage({ text: error, color: 'error' })
}
)
}
store/user.js mutations
const state = () => ({
user: null,
isAuthenticated: false
})
const mutations = {
setUser(state, payload) {
state.user = payload
},
setIsAuthenticated(state, payload) {
state.isAuthenticated = payload
}
}
store/user.js login action
userLogin({ commit }, { email, password }) {
return new Promise((resolve, reject) => {
auth
.signInWithEmailAndPassword(email, password)
.then((user) => {
console.log('logged in')
commit('setUser', user)
commit('setIsAuthenticated', true)
this.$router.push({
name: 'home'
})
resolve(true)
})
.catch((error) => {
commit('setUser', null)
commit('setIsAuthenticated', false)
this.$router.push({
path: '/'
})
reject(error)
})
})
},
When the login is clicked, the console is flooded with errors like
client.js?06a0:77 Error: [vuex] do not mutate vuex store state outside mutation handlers.
at assert (vuex.esm.js?2f62:90)
at Vue.store._vm.$watch.deep (vuex.esm.js?2f62:789)
at Watcher.run (vue.runtime.esm.js?2b0e:4568)
at Watcher.update (vue.runtime.esm.js?2b0e:4542)
at Dep.notify (vue.runtime.esm.js?2b0e:730)
at B.reactiveSetter [as a] (vue.runtime.esm.js?2b0e:1055)
at Tb (auth.esm.js?b7aa:27)
at B.k.Oc (auth.esm.js?b7aa:26)
at lc (auth.esm.js?b7aa:29)
at hc (auth.esm.js?b7aa:29)
It seems to have to do with the commit('setUser', user). As i am using v-model for the inputs (email,password) I tried slice() / making a copy of the input values to no effect. What am i missing here?
EDIT: Added template
<template>
...
<v-card-text>
<v-form
ref="loginForm"
v-model="valid"
lazy-validation
#submit.prevent="login()"
>
<v-text-field
v-model="loginData.email"
label="Email"
autofocus
clearable
:rules="[rules.required, rules.length]"
prepend-icon="mdi-account-circle"
#blur="resetValidation()"
/>
<v-text-field
v-model="loginData.password"
:type="showPassword ? 'text' : 'password'"
label="Password"
:rules="[rules.required]"
prepend-icon="mdi-lock"
:append-icon="showPassword ? 'mdi-eye' : 'mdi-eye-off'"
#click:append="showPassword = !showPassword"
#blur="resetValidation()"
/>
...

how to display spinner when data is being fetched from cloud firestore in vuejs?

i'm working on firebase and vuejs with vuex as well. so in onauthStateChanged() method i try to get all the data form posts collection. its takes some time to display, In meanwhile i want to display spinner that specifies the user where some something is being loading.
i tried and its works cool, but the problem with code is
<loadingSpinner v-if="loading"></loadingSpinner>
<div v-if="posts.length">
<div v-for="post in posts" v-bind:key=post.id class="post">
<h5>{{ post.userName }}</h5>
<span>{{ post.createdOn | formatDate }}</span>
<p>{{ post.content | trimLength }}</p>
<ul>
<li><a #click="openCommentModal(post)">comments {{ post.comments }}</a></li>
<li><a #click="likePost(post.id, post.likes)">likes {{ post.likes }}</a></li>
<li><a #click="viewPost(post)">view full post</a></li>
</ul>
</div>
</div>
<div v-else>
<p class="no-results">There are currently no posts</p>
</div>
Spinner component responsible for spin animation:
<loadingSpinner v-if="loading"></loadingSpinner>
And the below html code is for displaying data from firebase
Where posts and loading variables are the computed properties from vuex state
problem is when is reload the page, spinner showing along the
<div v-else>
<p class="no-results">There are currently no posts</p>
</div>
I want to restrict the v-else condition when the spinner is being loaded.
By the way, the loading computed properties is a boolean that reacts based on onAuthstateChanged() firebase method
this is my entire vuex store file :
import Vue from 'vue'
import Vuex from 'vuex'
const fb = require('./firebaseConfig.js')
Vue.use(Vuex)
// handle page reload
fb.auth.onAuthStateChanged(user => {
if (user) {
store.commit('setCurrentUser', user)
store.dispatch('fetchUserProfile')
fb.usersCollection.doc(user.uid).onSnapshot(doc => {
store.commit('setUserProfile', doc.data())
})
// realtime updates from our posts collection
fb.postsCollection.orderBy('createdOn', 'desc').onSnapshot(querySnapshot => {
// check if created by currentUser
let createdByCurrentUser
if (querySnapshot.docs.length) {
createdByCurrentUser = store.state.currentUser.uid == querySnapshot.docChanges[0].doc.data().userId ? true : false
}
// add new posts to hiddenPosts array after initial load
if (querySnapshot.docChanges.length !== querySnapshot.docs.length
&& querySnapshot.docChanges[0].type == 'added' && !createdByCurrentUser) {
let post = querySnapshot.docChanges[0].doc.data()
post.id = querySnapshot.docChanges[0].doc.id
store.commit('setHiddenPosts', post)
} else {
store.commit('setLoading', true)
let postsArray = []
querySnapshot.forEach(doc => {
let post = doc.data()
post.id = doc.id
postsArray.push(post)
})
store.commit('setPosts', postsArray)
store.commit('setLoading', false)
}
})
}
})
export const store = new Vuex.Store({
state: {
currentUser: null,
userProfile: {},
posts: [],
hiddenPosts: [],
loading: true
},
actions: {
clearData({ commit }) {
commit('setCurrentUser', null)
commit('setUserProfile', {})
commit('setPosts', null)
commit('setHiddenPosts', null)
},
fetchUserProfile({ commit, state }) {
fb.usersCollection.doc(state.currentUser.uid).get().then(res => {
commit('setUserProfile', res.data())
}).catch(err => {
console.log(err)
})
},
updateProfile({ commit, state }, data) {
let name = data.name
let title = data.title
fb.usersCollection.doc(state.currentUser.uid).update({ name, title }).then(user => {
// update all posts by user to reflect new name
fb.postsCollection.where('userId', '==', state.currentUser.uid).get().then(docs => {
docs.forEach(doc => {
fb.postsCollection.doc(doc.id).update({
userName: name
})
})
})
// update all comments by user to reflect new name
fb.commentsCollection.where('userId', '==', state.currentUser.uid).get().then(docs => {
docs.forEach(doc => {
fb.commentsCollection.doc(doc.id).update({
userName: name
})
})
})
}).catch(err => {
console.log(err)
})
}
},
mutations: {
setLoading(state, payload){
state.loading = payload
},
setCurrentUser(state, val) {
state.currentUser = val
// console.log(val)
},
setUserProfile(state, val) {
state.userProfile = val
// console.log(val)
},
setPosts(state, val) {
if (val) {
state.posts = val
} else {
state.posts = []
}
},
setHiddenPosts(state, val) {
if (val) {
// make sure not to add duplicates
if (!state.hiddenPosts.some(x => x.id === val.id)) {
state.hiddenPosts.unshift(val)
}
} else {
state.hiddenPosts = []
}
}
},
})
any suggestions?
I would tweak your v-if/v-else logic at bit.
<loadingSpinner v-if="loading" />
<div v-else-if="posts.length"></div>
<div v-else>
<p class="no-results">There are currently no posts</p>
</div>
The difference is v-else-if on posts.length, instead of v-if. This way, there are 3 distinct states.
Loading, show spinner.
Not loading, show posts.
Not loading, there are no posts, show no results.

Vue js - reload component on database insert

I have the following setup
Component.vue (display db collections as grid in main page)
...
<v-flex v-for="i in items" :key="i.id" xs6 sm3 md3>
<v-card color="primary">
<v-card-text>
<h2
class="font-weight-regular mb-4"
>
{{ i.description }}
</h2>
</v-card-text>
</v-card>
</v-flex>
...
<script>
import { db } from '~/plugins/firebase.js'
export default {
data: () => ({
items: []
}),
props: ['reload'],
watch: {
reload: function (newVal, oldVal) {
this.items = items
alert('changed reload')
}
},
methods: {
firestore() {
db.collection('items')
.get()
.then(querySnapshot => {
const items = []
querySnapshot.forEach(function(doc) {
const item = doc.data()
item.id = doc.id
items.push(useritem)
})
this.items = items
})
.catch(function(error) {
alert('Error getting documents: ' + error)
})
}
}
}
</script>
index.vue (main page that has grid component and button to add new collection)
....
<v-layout mb-4>
<v-btn
#click="submit"
>
Add Item
</v-btn>
</v-layout>
<v-layout mb-4>
<component :reload="reload" />
</v-layout>
....
<script>
import { db } from '~/plugins/firebase.js'
import component from '~/components/Component.vue'
import moment from 'moment'
export default {
components: {
component
},
data() {
return {
description: 'test',
date: moment(),
reload: false
}
},
methods: {
submit() {
db.collection('items')
.add({
description: this.description,
deadline: new Date(moment(this.date)),
status: true
})
.then(docRef => {
this.reload = true
})
.catch(error => {
alert('Error adding document: ', error)
})
}
}
}
</script>
As can be seen, I've added a prop to the component to sort of trigger a reload of data from database whenever a new item is added on the main page using the button.
On successful insert the value changes from false to true. However the component grid does not reload. Refreshing the page shows the new item in grid.
How can i make the component reactive or trigger reload on addition of new item?
In your firestore method in Component.vue, you are using the get method which according to the firestore documentation, only retrieves the data once, it doesn't listen to any change, you'd have to refresh your page to see your updated changes.
However, to listen to changes to your firestore DB and update accordingly on your website, you have to set a listener, Cloud Firestore sends your listener an initial snapshot of the data, and then another snapshot each time the document changes.
methods: {
firestore() {
db.collection("items").onSnapshot(
snapshot => {
const documents = snapshot.docs.map(doc => {
const item = doc.data();
item.id = doc.id;
return item;
});
this.items = documents;
},
error => {
// handle errors
alert("Error getting documents: " + error);
}
);
}

Vue Vuex Firebase Auth email sign in and update username

I've got firebase auth setup, however, I'm trying to update username before setting that to my current state. When I run everything before the update, everything works fine, but I dont have a username. I'm fairly new with js promises so I've tried running the function and returning the function, neither have really worked. My expectation is that by the time the dashboard screen shows, that the username is set.
Below is the code for signup via email which works without username.
store/user/index.js
signUserUp ({commit}, payload) {
commit('setLoading', true)
commit('clearError')
firebase.auth().createUserWithEmailAndPassword(payload.email, payload.password)
.then(function (user) {
return user.updateProfile({
displayName: payload.username
})
})
.then(
profile => {
commit('setLoading', false)
const newUser = {
id: profile.uid,
name: profile.username,
email: profile.email,
photoUrl: profile.photoURL
}
commit('setUser', newUser)
}
)
.catch(
error => {
commit('setLoading', false)
commit('setError', error)
console.log(error)
}
)
}
This is the code that returns an error and does not update the username until I refresh.
signUserUp ({commit}, payload) {
commit('setLoading', true)
commit('clearError')
firebase.auth().createUserWithEmailAndPassword(payload.email, payload.password)
.then(function (user) {
return user.updateProfile({
displayName: payload.username
})
.then(
profile => {
commit('setLoading', false)
const newUser = {
id: profile.uid,
name: payload.username,
email: profile.email,
photoUrl: profile.photoURL
}
commit('setUser', newUser)
}
)
.catch(
error => {
commit('setLoading', false)
commit('setError', error)
console.log(error)
}
)
},
My view is really simple just displaying the data.
<template>
<div>
<h1>Dashboard</h1>
<button #click="onLogout">Logout</button>
<hr>
<app-alert v-if="error" #dismissed="onDismissed" :text="error.message"></app-alert>
<img :if="user.photoURL" :src="user.photoUrl">
<h4><b>Display Name :</b> {{ user.name }}</h4>
<h4><b>Email :</b> {{ user.email }}</h4>
<h4><b>Email Verified :</b> {{ user.emailVerified }}</h4>
<h4><b>User ID :</b> {{ user.id }}</h4>
</div>
</template>
<script>
export default {
date () {
return {}
},
computed: {
user () {
return this.$store.getters.user
},
error () {
return this.$store.getters.error
}
},
methods: {
onLogout () {
this.$store.dispatch('logout')
this.$router.push('/')
},
onDismissed () {
this.$store.dispatch('clearError')
}
}
}
</script>
The errors I get back are an alert that states
Cannot read property 'uid' of undefined
And also, username does not display on the page component, even though it does display on page refresh.
Everything works fine up until I add this bit to try and update the username on user create, so this little bit doesn't pass the new updated user object.
.then(function (user) {
return user.updateProfile({
displayName: payload.username
})
})
Looks like my problem was in how I was sequencing my functions, in place of returning the user.updateProfile function, I was able to nest my updateProfile call like below, additionally, I was calling username as the object username when it should've been displayName.
signUserUp ({commit}, payload) {
commit('setLoading', true)
commit('clearError')
firebase.auth().createUserWithEmailAndPassword(payload.email, payload.password)
.then(function (user) {
user.updateProfile({
displayName: payload.username
}).then(
() => {
commit('setLoading', false)
const newUser = {
id: user.uid,
name: user.displayName,
email: user.email,
emailVerified: user.emailVerified
}
commit('setUser', newUser)
}
).catch(
error => {
commit('setLoading', false)
commit('setError', error)
console.log(error)
}
)
})
.catch(
error => {
commit('setLoading', false)
commit('setError', error)
console.log(error)
}
)
},

Resources