Unable to save username with AsyncStorage in react native - javascript

I am unable to save username with AsyncStorage in my app.
I am using Switch component, if the value is true, username is saved and on logout the username should persist.
AsyncStorage returns undefined
// function for user to toggle if username should be saved
toggleRememberMe = value => {
this.setState({ rememberMe: value })
if (value === true) {
//user wants to be remembered.
this.rememberUser();
} else {
this.forgetUser();
}
}
// function to save username
rememberUser = async () => {
try {
await AsyncStorage.setItem('user_userID', this.state.signInEmail);
} catch (error) {
console.log(error)
}
};
// function to get username
getRememberedUser = async () => {
try {
const username = await AsyncStorage.getItem('user_userID');
if (username !== null) {
return username;
}
} catch (error) {
console.log(error)
}
};
// function to forget username or remove
forgetUser = async () => {
try {
await AsyncStorage.removeItem('user_userID');
} catch (error) {
console.log(error)
}
};
// componentDidMount
async componentDidMount() {
const username = await this.getRememberedUser();
console.log(username)
this.setState({
signInEmail: username || "",
rememberMe: username ? true : false });
}
//render
<Switch
trackColor={{true: '#16752A'}}
value={this.state.rememberMe}
onValueChange={(value) => this.toggleRememberMe(value)}
/>
<Text>Remember Me</Text>
How can I resolve this?

Related

updateProfile is not a function (Firebase)

I am learning React but when I register a user(using createUserWithEmailAndPassword) and try to update the displayName property I get the error as "user1.updateProfile is not a function".
How can I solve this error?
My code:
const register = async (e) => {
if (name.length == 0) {
alert("name cannot be empty");
} else {
const userWithEmailAndPassword = await createUserWithEmailAndPassword(auth, email, password)
.then((auth1) => {
const user1 = auth.currentUser;
user1.updateProfile({
displayName: name
});
})
.catch(error => alert(error.message))
console.log(userWithEmailAndPassword);
}
}
The updateProfile function needs to be imported from Firebase Auth SDK directly when using the Modular SDK as shown below:
import { createUserWithEmailAndPassword, updateProfile } from "firebase/auth"
const register = async (e) => {
if (name.length == 0) {
alert("name cannot be empty");
} else {
const { user } = await createUserWithEmailAndPassword(auth, email, password)
console.log(`User ${user.uid} created`)
await updateProfile(user, {
displayName: name
});
console.log("User profile updated")
}
}

Accessing value from dispatch

export async function signIn({ dispatch }, data) {
Loading.show()
firebaseAuth
.signInWithEmailAndPassword(data.email, data.password)
.then(async res => {
Loading.hide()
// if (!res.user.emailVerified) {
// dispatch('setNotification', {
// ...failed,
// message: 'Email not verified!'
// })
// return
// }
res.user.getIdToken().then(token => {
Loading.hide()
const { uid } = res.user
tempStorage.token = token
tempStorage.localId = uid
storage.delete(StorageKeys.token)
storage.set(StorageKeys.token, token)
storage.set(StorageKeys.localId, uid)
dispatch('setNotification', {
...success,
message: 'Successfully login!'
})
dispatch('getUserProfile')
// i need to access the value here from getUserProfile function
})
})
.catch(error => {
Loading.hide()
var msg = ''
switch (error.code) {
case 'auth/wrong-password':
msg = 'Wrong password'
break
case 'auth/user-not-found':
msg = 'User not found'
break
case 'auth/too-many-requests':
msg = 'Account temporarily suspended'
}
dispatch('setNotification', {
...failed,
message: msg
})
})
}
export async function getUserProfile({ dispatch, commit }) {
try {
const serviceUrl = `${urls.users}/${tempStorage.localId}`
const { data } = await request.get(serviceUrl)
commit('setUser', data)
} catch (err) {
console.log(err, 'err')
}
}
How do i access the value from this disptach(getUserProfile) function???
if (data.attributes.roles.includes('admin')) {
this.$router.push({ path: routesConfig.name.training })
} else {
this.$router.push({ path: routesConfig.name.profile })
}
i want this condition to run on basis of dispatch function
result and the upper condition will redirect me to different pages on basis of role
Thanks in advance!

Firebase custom user claims are not set

I am trying to add custom user claims after user sign up, to define user role, using setCustomUserClaims:
/api/users/addUser.js
export default async (req, res) => {
const { displayName, email, password, role } = req.body;
if (!displayName || !password || !email || !role) {
return res.status(400).send({ message: 'Missing fields' });
}
try {
const { uid } = await admin.auth().createUser({
displayName,
email,
password,
});
await admin.auth().setCustomUserClaims(uid, role);
res.status(201).send(uid);
} catch (error) {
handleError(res, error);
}
};
This code checks for any change in the authentication state and sets user to the currently logged in user:
/utils/use-auth.js
useEffect(() => {
const unsubscribe = firebase.auth().onAuthStateChanged((user) => {
if (user) {
setUser(user);
} else {
setUser(false);
// Router.push('/login');
}
});
in my /pages/user/home,jsx:
import { useAuth } from '../../utils/use-auth';
function home() {
const { user } = useAuth();
return (
<div>
<pre>{JSON.stringify(user, null, 4)}</pre>
<AdminLayout componentProps={{ selected: '1' }} Component={HomeContent} />
</div>
);
}
The displayed object doesn't have any custom claims.
when I check the firebase console, I find that the user is actually added.
Try using
admin.auth().setCustomUserClaims(uid, claims).then(() => {
// Do your stuff here
});
And verify the claims like
admin.auth().verifyIdToken(idToken).then((claims) => {
// check claims
if (claims) {
// do your stuff here
}
});
for more info check https://firebase.google.com/docs/auth/admin/custom-claims#node.js

How to fix TypeError: Converting circular structure to JSON at JSON.stringify (<anonymous>) in react-native

I need to store firebase authentication token as a user in react native asyncstorage. here is my code.
loginUser = async (email, pw) => {
if (this.state.isConnected) {
if (email != '' && pw != '') {
try {
let user = fb.auth().signInWithEmailAndPassword(email, pw).catch((err) => {
alert('Invalid email or password');
});
this.storeUser(JSON.stringify(user))
console.log(user);
} catch (error) {
console.log(error);
}
}
}
}
storeUser = async (user) => {
try {
await AsyncStorage.setItem('User', JSON.stringify(user)).then(() => {
console.log("Success user");
})
} catch (e) {
console.log(e);
}
}
but it gives me this error
TypeError: Converting circular structure to JSON
at JSON.stringify (<anonymous>)
can anyone help me with this?
There is an incorrect usage of the signInWithEmailAndPassword(email, pw) function call, the firebase.auth.signInWithEmailAndPassword() function returns a Promise<UserCredential> object which will error out when you call JSON.stringify() on it.
The returned UserCredential object needs to be retrieved from the Promise by using the then() method of the Promise class. See below:
try {
fb.auth().signInWithEmailAndPassword(email, pw).then(function(userCred) => {
this.storeUser(userCred);
console.log(JSON.stringify(userCred)); // so you can see a JSON string in the logs
}).catch((err) => {
alert('Invalid email or password');
});
}
Disclaimer: As the entire function is not shown, play with the above
From Above Code the mistake is converting two times
await AsyncStorage.setItem('User', user).then(() => {
Updated Code :
loginUser = async (email, pw) => {
if (this.state.isConnected) {
if (email != '' && pw != '') {
try {
let user = fb.auth().signInWithEmailAndPassword(email, pw).catch((err) => {
alert('Invalid email or password');
});
this.storeUser(JSON.stringify(user))
console.log(user);
} catch (error) {
console.log(error);
}
}
}
}
storeUser = async (user) => {
try {
await AsyncStorage.setItem('User', user).then(() => {
console.log("Success user");
})
} catch (e) {
console.log(e);
}
}

Firebase create user with email and password and put data in database

I want to create users with the function createUserWithEmailAndPassword and then put the data of that user into my database but it doesn't work.. the user is added to my authentication tab in firebase but not in my database. I also don't get an error.
registerUser.addEventListener('click', function (user) {
event.preventDefault();
closeRegisterForm();
email = registerEmail.value;
password = registerPassword.value;
firebase.auth().createUserWithEmailAndPassword(email, password)
.then(function (event) {
var ref = firebase.database().ref("users").child(user.uid).set({
email: user.email,
uid: user.uid
});
})
.catch(function (error) {
var errorCode = error.code;
var errorMessage = error.message;
});
});
Hi I was having the exact same problem. But i used a local function to solve it. Something like this:
createNewUser(form) {
//create new user with provided data of the form
this.afAuth.auth.createUserWithEmailAndPassword(form.email, form.password)
.then(function(firebaseUser) {
console.log("User " + firebaseUser.uid + " created successfully!");
updateFirestore(form, firebaseUser.uid);
return firebaseUser;
}).catch(function(error) {
alert(error)
});
function updateFirestore(form, uidNewUser) {
//push data into firestore using the uid provided
let data = {};
data['mail'] = form.email;
data['name'] = form.name;
//se empuja el arreglo data en el documento del usuario
this.afs.collection('users').doc(uidNewUser).set(data);
console.log(data, uidNewUser);
}
}
You refer to user.uid and user.email but never define user. The return type of sign in method createUserWithEmailAndPassword is a user but you define it as event. Also make sure you wait for the db write promise to resolve and catch any errors there as Frank advised.
Working for me:
const val = this.signupForm.value;
this.authService.doRegister(val)
.then(res => {
this.msg = 'You have registered successfully!';
this.msgType = 'success';
this.authService.updateUser(val.name, null)
.then(suc => {
const created = firebase.firestore.FieldValue.serverTimestamp();
const user = {
first_name: val.name,
last_name: '',
email_personal: val.email,
created: created,
updated: created
};
this.userCollection = this.afs.collection<User>('users');
this.userCollection.doc(suc).set(user);
}, err => {
// console.log(err);
});
this.router.navigate(['/']);
}, err => {
this.msg = err.message;
})
const [phone, setPhone] = useState()
const [email, setEmail] = useState()
const [password, setPassword] = useState()
const handleSignUp = async () => {
if (!email == ' ' && !password == ' ') {
try {
const result = await auth().createUserWithEmailAndPassword(email, password)
firestore()
.collection('Users')
.doc(result?.user?.uid)
.set({
email: result?.user?.email,
phoneNumber: phone,
uid: result?.user?.uid,
displayName: result?.user?.email.split('#')[0],
})
.then(() => {
alert('User added!');
});
} catch (error) {
if (error.code === 'auth/email-already-in-use') {
Alert.alert('That email address is already in use!');
}
else if (error.code === 'auth/invalid-email') {
Alert.alert('That email address is invalid!');
}
else {
Alert.alert(error)
}
}
} else {
Alert.alert("Please Enter Your All Field");
}
}

Categories

Resources