I'm using @reduxjs/toolkit: 1.7.1
, firebase: 9.6.1
and firebase-tools: 10.0.1
on my ReactJS project. I was trying to create a function where users can update their names and avatar photos.
For which I used updateProfile()
function. But whenever I execute the update function it threw an error Cannot assign to read only property 'displayName' of object '#<Object>'
.
There is an interesting thing I have noticed that is if I only update the photoURL property still it gives Cannot assign to read only property 'displayName' of object '#<Object>'
Code: useFirebase.js
:
`import { getAuth, signInWithPopup, GoogleAuthProvider, createUserWithEmailAndPassword, signInWithEmailAndPassword, signOut, onAuthStateChanged, updateProfile } from 'firebase/auth';
import { getDownloadURL, getStorage, ref, uploadBytes } from 'firebase/storage';
import { useEffect, useState } from 'react';
import { useDispatch } from 'react-redux';
import { useLocation, useNavigate } from 'react-router-dom';
import { setIsLoading } from '../features/isloadingSlice';
import { login, logout } from '../features/userSlice';
import initAuth from '../Firebase/initAuth';
initAuth();
export const useFirebase = () => {
const auth = getAuth();
const location = useLocation();
const navigate = useNavigate();
const dispatch = useDispatch();
const [updateCount, setUpdateCount] = useState(0);
const storage = getStorage();
const Redirect = () => {
console.log(location);
const destination = location?.state?.from?.pathname || '/';
navigate(destination);
}
const uploadAvatar = async (file) => {
const fileRef = ref(storage, 'avatar/' + auth?.currentUser?.uid + '.png');
dispatch(setIsLoading(true));
const snapshot = await uploadBytes(fileRef, file);
const photoURL = await getDownloadURL(fileRef);
updateProfile(auth.currentUser, { photoURL }).then(() => {
setUpdateCount(updateCount + 1);
}).catch(e => console.log(e.message))
dispatch(setIsLoading(false));
console.log(snapshot);
}
const userRegister = (name, photoURL, email, password) => {
dispatch(setIsLoading(true));
createUserWithEmailAndPassword(auth, email, password)
.then(result => {
updateProfile(auth.currentUser, {
displayName: name, photoURL
}).then(() => { })
dispatch(login({ displayName: name, email, photoURL }));
Redirect();
}).catch(error => alert(error.message))
.finally(() => dispatch(setIsLoading(false)))
}
useEffect(() => {
const unsubscribe = onAuthStateChanged(auth, (result) => {
if (result) {
dispatch(login({ ...result }))
}
else {
dispatch(login({}))
}
dispatch(setIsLoading(false));
})
return () => unsubscribe;
}, [updateCount, auth])
return {
logIn,
logOut,
Redirect,
uploadAvatar,
userRegister,
}
}`
I don't know what's wrong with this displayName
property but my previous project works fine.
Can anybody please help me with this?
Top comments (0)