How to access a firestore doc that has been created for my users on account creation so they can update/add user information

Viewed 50

I have a cloud function that successfully creates a document in a collection called 'users', this doc generates an auto ID and saves their email upon them creating an account. The problem I'm having is accessing this document so the user can submit a form in the UI and update/add information such as; username, first name, profile pic, birthday, etc...

My pop-out form in the UI is working correctly ie it closes when I press submit button, but the data I input is being written into the localhost URL. - I'm thinking this is because it is not connecting to firestore in some way.

Code in auth.js file All imports

import { createUserWithEmailAndPassword, onAuthStateChanged, signInWithEmailAndPassword } from "firebase/auth";
import { db, auth } from "./firebase";
import { doc, setDoc } from "firebase/firestore";

In order of sequence

// Initiate firebase auth
export function initFirebaseAuth() {
    // Listen to auth state changes.
    onAuthStateChanged(auth, authStateObserver);
};

// some DOM hide element functions

// Triggers when the auth state change for instance when the user signs-in or signs-out.
function authStateObserver(user) {
    if (user !== null) {
        const displayName = user.displayName;
        const email = user.email;
        console.log(displayName, email + ' is logged in')

        // User is signed in! Show on Profile info
        displayUser.appendChild(displayUserEmail);
        displayUserEmail.textContent = `Logged in as: ${user.email}`;

        // Get the signed-in user's profile pic and name.
        var profilePicUrl = getProfilePicUrl();
        var userName = getUserName();

        // Set the user's profile pic and name.
        userPicElement.style.backgroundImage =
            'url(' + addSizeToGoogleProfilePic(profilePicUrl) + ')';
        userNameElement.textContent = userName;

        // Show user's profile and sign-out button.
        // Hide sign-in button.
        userIsLoggedIn();

        // show post form
        shareContent.removeAttribute('hidden');

        // We save the Firebase Messaging Device token and enable notifications.
        // saveMessagingDeviceToken();
    } else {
        // User is signed out!
        console.log('no user is logged in ');
        // Hide user's profile and sign-out button.
        // Show sign-in button.
        noUserLoggedIn();

        // hide post form
        shareContent.setAttribute('hidden', 'true');
    }
    // return user, displayName, email, photoURL, emailVerified, uid;
};


// Returns the signed-in user's profile Pic URL.
export function getProfilePicUrl() {
    return auth.currentUser.photoURL || '/Assets/Images/profile_placeholder.png';
};

// Returns the signed-in user's display name.
function getUserName() {
    return '@' + auth.currentUser.displayName || 'Create Username';
};

User Signup Form

// create Account
if (signUpForm) {
    signUpForm.addEventListener('submit', (e) => {
        e.preventDefault();

        //get user info
        const email = signUpForm['signupEmail'].value;
        const password = signUpForm['signupPassword'].value;

        createUserWithEmailAndPassword(auth, email, password).then((cred) => {
            // hide signup form and show profile edit form - reset signup form
            hideSignUpModal();
            profileModal.classList.remove('hidden');

            // reset form
            signUpForm.reset();
            document.getElementById("signUpErr").innerHTML = "";
            //return user 
            console.log(user);
            console.table(cred);
        })
        .catch(err => {
            document.getElementById("signUpErr").innerHTML = err.message;
        })
    })
}

login form

// login form
loginForm.addEventListener('submit', (e) => {
    e.preventDefault();

    const email = loginForm['loginUsername'].value;
    const password = loginForm['loginPassword'].value;

    signInWithEmailAndPassword(auth, email, password)
    .then(() => {
        // hide login form
        hideLoginModal();

        // reset form
        loginForm.reset();
        // ...
        document.getElementById("loginErr").innerHTML = "";
    })
    .catch((err) => {
        document.getElementById("loginErr").innerHTML = err.message;
    });
});

const logout = document.querySelector('#logout');
if (logout) {
    logout.addEventListener('click', (e) => {
        if (!e.target.closest('.transBtn')) return;
        auth.signOut().then(() => {
            console.log('user signed out')
        });
    });

};

profile edit form

// some DOM element hide/show code

// checking for user ID
const currentUserId = auth.currentUser.uid;
console.log(currentUserId);

// edit profile
editProfileButton.addEventListener('submit', (e) => {
    e.preventDefault();
    return setDoc(doc(db, 'users', cred.user.uid), {
        photoURL: newProfilePicURL(),
        displayName: userNameInputElement.value,
        firstName: firstNameInputElement.value,
        lastName: lastNameInputElement.value,
        birthday: birthdayInputElement.value
    })
    .then(() => {
        console.log(`updated ${displayName}'s user info`);
        alert('Your profile information has been saved!');
        // Profile updated!
        profileModal.setAttribute('hidden', 'true');
        // ...
    }).catch((error) => {
        // An error occurred
        console.error('Error Firebase Database', error.message);
        // ...
    })
})

initFirebaseAuth();
hideLoginModal();
hideSignUpModal();
hideProfileModal();
0 Answers
Related