Issue saving user object to Firebase realtime database - javascript

Im using the firebase authentication function which returns a user object as follows:
auth()
.createUserWithEmailAndPassword(email, password)
.then(user => {
Im then trying to save this user object to the Firebase database like so
database()
.ref('profiles/users/' + user.user.uid)
.set({
myUserObj: user,
})
However firebase database is returning an error 'Cannot read property 'code' of undefined' FULL CODE BELOW
auth()
.createUserWithEmailAndPassword(email, password)
.then(user => {
console.log(user.user);
database()
.ref('profiles/users/' + user.user.uid)
.set({
myUserObj: user,
})
.catch(err =>
console.log(err.message),
);
})

Firebase Realtime Database can only store valid JSON objects. The UserCredential object contains many methods, which makes it not a valid JSON object.
You could give it a try to save it with:
database()
.ref('profiles/users/' + user.user.uid)
.set({
myUserObj: JSON.parse(JSON.stringify(user)),
})
If this doesn't work, you'll have to explicitly name the properties that you want to save.

Related

Login function saving token to localStorage as [Object][Object] [duplicate]

This question already has answers here:
How to store objects in HTML5 localStorage/sessionStorage
(24 answers)
Closed 11 months ago.
I am trying to login to my user account which is saved on database and attach a token to that username with 'jwt-token'.
router.post('/users/login', (req, res) => {
User.authenticate()(req.body.username, req.body.password, (err, user) => {
if (err) { console.log(err) }
res.json(user ? jwt.sign({ id: user._id }, process.env.SECRET) : null)
})
})
However when i login to the account, the token is being saved, as [Object][Object] in the local storage via this function here,
// when a user clicks login
const handleLogin = (event) => {
event.preventDefault();
axios.post('/api/users/login', {
username: userState.username,
password: userState.password
}).then(token => {
console.log(token)
setLoginState(true)
localStorage.setItem('username', userState.username)
localStorage.setItem('token', token)
}).catch(err => { console.log(err) })
What is the reason the token is saving as an object? is it not properly being created by my route? or am I not calling it correctly in my .then call? any insight would be appreciated. Still trying to learn as much as i can on backend work and seem to hit problems at every step.
We have to stringify while storing objects in storage and parse the stored objects while retrieving.
// Put the object into storage
localStorage.setItem('username', JSON.stringify(username));
// Retrieve the object from storage
var retrievedUsername= localStorage.getItem('username');
console.log('retrievedUsername: ', JSON.parse(retrievedUsername));
localStorage.setItem() saves information as Strings which is why you see "[Object][Object]" being saved since that is what it is receiving.
So you need to transform your object to a String before you save it.
You can achieve this by using the JSON.stringify() function.
Note: you will have to transform the String back to an object when you need to get it.
You can achieve this by using the JSON.parse()
Example:
localStorage.setItem('username', JSON.stringify(userState.username))
localStorage.setItem('token', JSON.stringify(token))
JSON.parse(localStorage.getItem('username'))
JSON.parse(localStorage.getItem('token'))
axios promise returns response object which has a data attribute. To access token you should call
res.data
and store it like so
localStorage.setItem('token',res.data)

How can I fix this issie with logging in users and storing them in a firestore database?

This code i used to store users in firebase.
this.db
.doc('/users/' + user.uid)
.set({
name: user.displayName,
email: user.email,
})
.then(() => console.log('user saved successfully'))
.catch((reason: any) => console.log('user save failed:', reason));
Users also have a isAdmin property that gets set elsewhere.
When I login as a new user, the user gets a name and email.
If i make the user admin i can visit admin only pages.
issue is, if i refresh on an admin page i get kicked of the page.
I think the issue is the set method, since it doesnt contain the isAdmin property
When I use update instead of set, it works fine when I refresh, but now I cant create new records for new users.
What is the best way to tackle this?
You're looking to merge the data in your set call with the existing data (if any), which you can do by specifying set options:
this.db
.doc('/users/' + user.uid)
.set({
name: user.displayName,
email: user.email,
}, { merge: true }) // 👈
Also see: https://firebase.google.com/docs/firestore/manage-data/add-data#set_a_document

How to save a user to the firestore database during registration? So far, it is saved only in the Authentication of the firestore

How can I save a user to the firestore database during registration? So far, it is saved only in the Authentication of the firestore.
this is my code now
registerWithEmail(email:string, password:string){
this.auf.createUserWithEmailAndPassword(email, password)
.then((user) => {
this.authState = user
})
.catch((error) => {
console.log(error)
throw error
})
}
One way to get started:
this.auf.createUserWithEmailAndPassword(email, password)
.then((user)=>{
this.authState = user
firebase.firestore().collection(users).doc(user.uid).set({
email: email
})
})
But there are dozens (if not hundreds) of tutorials out there, so if you haven't tried anything yet, I recommend starting with those: https://www.google.com/search?q=save+user+data+the+firestore+during+registration+in+javascript

Unable to get updated attributes and their values from cognito with aws-amplify

Unable to get current attributes and their values from Cognito
Here is the complete flow of what I did
successfully logged in with aws-amplify
const cognitoUser = await Auth.currentAuthenticatedUser();
console.log("cognitoUser", cognitoUser);
got the Cognito user attributes info which is all correct (name, sub, email, email_verified)
called a backend API to update the user info (added one more attribute "profile": 1)
checked from Cognito user pool, it was successfully added and "profile": 1 was there
again I did const cognitoUser = await Auth.currentAuthenticatedUser();
console.log("cognitoUser", cognitoUser);
got the old result again (name, sub, email, email_verified). "profile": 1 was not there
successfully signed out with aws-amplify
logged in again
the keys this time got from the console.log are (name, sub, email, email_verified, profile)
after searching a lot I found the answer.
there is something called bypass cache. this is how we can use it
import { Auth } from 'aws-amplify';
Auth.currentAuthenticatedUser({
bypassCache: false // Optional, By default is false. If set to true, this call will send a request to Cognito to get the latest user data
}).then(user => console.log(user))
.catch(err => console.log(err));

How to get array from firebase firestore

I'm doing a react project for download movies . In this project user can like to movie and add to watchlist. I need to get array of like and store it on browser local storage . I need to know how to get array from firestore .
This is path of array I need to get.
users > {user id} > likes
This is what I tried.
firebase
.firestore()
.collection("users")
.doc(firebase.auth().currentUser.uid)
.collection("likes")
.get()
.then((likes) => {
console.log(likes)
});
.collection("likes") likes is a field not a collection so to get likes field you have to read whole document.
Try like this
firebase
.firestore()
.collection("users")
.doc(firebase.auth().currentUser.uid)
.get()
.then((user_doc) => {
console.log(user_doc.data())
});

Categories

Resources