I want to add the username on the signup of the user and I am using the following code:
//Create Account With Email&Password
const createUser = (email, password, username) => {
return createUserWithEmailAndPassword(auth, email, password).then(() => {
updateProfile(auth.currentUser, {
displayName: username,
});
});
};
This is my useEffect in the same js file
useEffect(() => {
console.log('useEffect');
const unsubscribe = onAuthStateChanged(auth, (currentUser) => {
setUser(currentUser);
});
return () => unsubscribe();
}, []);
This code is adding the displayname successfully, but when I redirect to my account page the displayname is not directly showing up and I am getting a memory leak warning from the router-dom. Is there a cleaner and better way to do this?
I believe it's because the account page loads before firebase loads the auth data, you can use something like
onAuthStateChanged(auth,(user)=>{
if(user){
getUserName = auth.currentUser.displayName;
// Load the rest of the page
}
}
at your redirected user page,assuming you are using the right auth state, which you can refer from here https://firebase.google.com/docs/auth/web/auth-state-persistence?authuser=0
Related
I am collecting name, email, phone and password when a user sign up. In the useFirebase hook, I am updating the displayName using updateProfile method of firebase.
This function is used for creating user.
const userCreate = (name, email, password, phone, history) => {
createUserWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
//User Create after registration
const newUser = { email, displayName: name, phoneNumber:phone };
const uid = auth.currentUser.uid
verifyEmail();
updateProfile(auth.currentUser, {
displayName: name,
phoneNumber:phone,
})
.then(() => {
console.log()
})
.catch((error) => {
});
history.replace('/');
})
.catch((error) => {
console.log(error)
})
}
After signup the displayName is updated. But I am not getting the phone number. How can I do that?
From the documentation on updating a user's profile:
You can update a user's basic profile information—the user's display name and profile photo URL—with the updateProfile method.
So there's no way to update the user's phone number with this function. The reason for this is that the phone number is part of a user's sign-in credentials, so needs to be updated through a dedicated method (similar to their password and email).
To update a user's phone number, call the updatePhoneNumber function as shown here:
// 'recaptcha-container' is the ID of an element in the DOM.
const applicationVerifier = new RecaptchaVerifier('recaptcha-container');
const provider = new PhoneAuthProvider(auth);
const verificationId = await provider.verifyPhoneNumber('+16505550101', applicationVerifier);
// Obtain the verificationCode from the user.
const phoneCredential = PhoneAuthProvider.credential(verificationId, verificationCode);
await updatePhoneNumber(user, phoneCredential);
I have an application that logs in both by email and password and by GoogleAuth, but after logged in, if the user reloads the page, it logs out.
I'm trying to manage GoogleAuthProvider, signInWithEmailAndPassword and setPersistence. For this example, just follow the login function with Google. I did it as follows:
Login.vue
import { getAuth, setPersistence, inMemoryPersistence, GoogleAuthProvider, signInWithPopup, } from "firebase/auth";
googleSignIn: function() {
const auth = getAuth();
const provider = new GoogleAuthProvider();
signInWithPopup(auth, provider)
.then(() => {
setPersistence(auth, inMemoryPersistence);
this.$router.push("/");
})
.catch((error) => {
// error messages
}
});
},
I'm trying to apply what I saw here: https://firebase.google.com/docs/auth/web/auth-state-persistence
On the other hand, in the parent component (after logging in), I'm getting the user data without any problems as follows:
Header.vue
import { getAuth, onAuthStateChanged } from "firebase/auth";
export default {
date: () => ({ username: "" }),
created() {
const auth = getAuth();
onAuthStateChanged(auth, (user) => {
if (user) {
this.username = user.displayName;
} else {
this.username = "logged out";
}
});
},
};
EDIT
I'm including the data saved in the application here. Even so, when reloading the user logs out.
On browser environments the default behavior for Firebase Authentication is to persist the user authentication state between page loads, and there is no need to call setPersistence yourself. I recommend removing this call from your code, and leaving it to the Firebase SDK to use its defaults.
That's the intended behavior. You are setting auth persistence to inMemoryPersistencce. The documentation says,
NONE (inMemoryPeristence) indicates that the state will only be stored in memory and will be cleared when the window or activity is refreshed.
Try setting the persistence to SESSION or LOCAL.
If I open dev tools, I can see I am authenticated. The issue seems to be with your redirect here:
router.beforeEach((to, from, next) => {
// This currentUser maybe undefined
const currentUser = getAuth().currentUser;
// ...
else next();
});
Try using onAuthStateChanged() in the beforeEach:
router.beforeEach((to, from, next) => {
const auth = getAuth()
onAuthStateChanged(auth, (user) => {
if (!user) return next("login");
})
})
I have the user inside localstorage, when user logouts the localstorage data becomes NULL. When user logins, the localstorages fills with user's data but to check this my userEffect in App.js do not reflect any change.
i have signUp
dispatch(signin(form, history));
history.push("/"); //go back to App.js file
in Navbar the user data changes
const Navbar = (props) => {
const [user, setUser] = useState(JSON.parse(localStorage.getItem("profile")));
const logout = () => {
dispatch({ type: "LOGOUT" });
dispatch({
type: "EMPTY_CART",
});
history.push("/");
setUser(null);
};
now at App.js i have
const user = JSON.parse(localStorage?.getItem("profile"));
const getCartItems = useCallback(async () => {
if (user) {
console.log("Yes user exixts");
dispatch(getEachUserCart(user?.result?._id));
} else {
console.log("No user exist");
}
}, []); //
useEffect(() => {
getCartItems();
}, [getCartItems]);
Now if u look above, after dispatching signUp action, i come back to App.js but here the useEffect don't run nor it checks if user have changed.
Hey – looks like you have a missing dependency issue. You need to have it like so
const getCartItems = useCallback(async () => {
if (user) {
console.log("Yes user exixts");
dispatch(getEachUserCart(user?.result?._id));
} else {
console.log("No user exist");
}
}, [user]);
Otherwise, this function will never be redeclared with the latest user value. Kindly let me know if that helps
I have a react app with which I want to handle authentication with firebase.
My code successfully signs up and logs in but i am trying to add extra information on sign up but i have not been successful. I have tried answers [here]: Firebase v3 updateProfile Method and [here]: Firebase user.updateProfile({...}) not working in React App
But they don't seem to work. Below is my code
const SignUp = ({ history }) => {
const handleSignUp = useCallback(
async event => {
event.preventDefault();
const { email, password } = event.target.elements;
try {
let cred = await app
.auth()
.createUserWithEmailAndPassword(email.value, password.value);
await cred.user.updateProfile({
displayName: 'hello'
});
history.push('/');
} catch (error) {
console.log(error);
}
},
[history]
);
Please how do i fix this because currently on the email and username sets? Thanks
In order to change user profile you should use firebase.auth().onAuthStateChanged() function, as follows:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
} else {
// No user is signed in.
}
});
Then you can get others user properties. Here you can find all info you need. https://firebase.google.com/docs/auth/web/manage-users. Hope it helps.
In my app, users can sign up with their email address and password (all with Firebase) and by default the user's wont have their displayName and photoURL set if they sign up with email/password. Which is why I'm trying to update their profile in the moment they submit the sign up form by adding those 2 fields.
After a successful sign up, the users get redirected to the protected Home page where I'm trying to display, you guessed it, their displayName and photo (photoURL) BUT, even if I set those fields, the Home page doesn't pick it up on time and I always have to refresh the page for those details to appear.
Can I have some help with this please?\
onSubmit = event => {
const { displayName, photoURL, email, passwordOne } = this.state;
const { history } = this.props; /* eslint-disable-line */
authFunctions
.doCreateUserWithEmailAndPassword(email, passwordOne)
.then(session => {
auth.currentUser.updateProfile({
displayName,
photoURL
});
db.doCreateUser(session.user.uid, displayName, photoURL, email)
.then(() => {
this.setState({ ...INITIAL_STATE });
history.push(routes.HOME);
})
.catch(error => {
this.setState(byPropKey('error', error));
});
})
.catch(error => {
this.setState(byPropKey('error', error));
});
event.preventDefault();
};
As you can see on my code, I'm creating the users on Firebase and then adding them to the database as well. I'm trying to update the profiles right after I create the actual user but for some reason it doesn't pick it up.
You are updating the Firebase User profile and creating the user profile in the database simultaneously. It is most likely routing to the home screen before the update can finish.
return auth.currentUser.updateProfile({ displayName, photoURL }).then(() => {
db.doCreateUser(session.user.uid, displayName, photoURL, email).then(() => {
this.setState({ ...INITIAL_STATE });
history.push(routes.HOME);
})
})
Add a then after updating the Firebase User and 'then' create the user profile in the database.