Search code examples
javascriptreactjsfirebaseredux

snapchot error firebase (reading 'onSnapshot')


i have a firebase issue, whenever I try to authenticate with firebase i get this problem App.js:27 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'onSnapshot') App.js :

{
  const {setCurrentUser} = this.props
this.authListener = auth.onAuthStateChanged(async userAuth =>{
  if(userAuth)
  {
    const userRef = await handleUserProfile(userAuth)
    userRef.onSnapshot(snapchot=>{
      setCurrentUser(
        {
          id:snapchot.id,
          ...snapchot.data(),
        }
      )
    })
  }
  setCurrentUser(userAuth)
})
}

firebase.js :

export const handleUserProfile = async({ userAuth, additionalData }) => {
    if (!userAuth) return;
    const { uid } = userAuth;

    const userRef = firestore.doc(`users/${uid}`);
    const snapshot = await userRef.get();

    if (!snapshot.exists) {
        const { displayName, email } = userAuth;
        const timestamp = new Date();
        const userRoles = ['user'];

        try {
            await userRef.set({
                displayName,
                email,
                createdDate: timestamp,
                userRoles,
                ...additionalData
            });
        } catch (err) {
            console.log(err);
        }
    }

    return userRef;
};

I cant get eventually the redux state of the currentUser, I am trying to save the currentUser when is logged in :

const mapStatetoProps = ({user}) =>
({
currentUser:user.currentUser
})  
const mapDispatchToProps = dispatch =>({
  setCurrentUser:user => dispatch(setCurrentUser(user))
})
export default connect(mapStatetoProps,mapDispatchToProps)(App)

Solution

  • Here you are destructuring userAuth from the object you receive as a parameter in this function

    export const handleUserProfile = async({ userAuth, additionalData }) => {

    And here you are directly passing the userAuth:

    const userRef = await handleUserProfile(userAuth)

    Instead, here you should write:

        const userRef = await handleUserProfile({userAuth})
    

    This will pass the userAuth in an object, hence the destructuring will be successful!