firebaseDashboard.js

    0

    0

    Dashboard is a React component.

    The code starts by getting the user's authentication state. It uses useAuthState to get the user and loading and error . Next, it uses useState to set the name and setName to an empty string.

    Next, it uses useNavigate to set up a fetchUserName function. This function will query the users collection and return the user's data. If there is an error, the error will be logged and the button will be disabled.

    The last part of the code is the useEffect . This function will execute if the loading variable is true . If the user is not logged in, it will navigate to the / page. Finally, the fetchUserName function will be executed.

    Library: react

    import { auth, db, logout } from "./firebase";
    import { useAuthState } from "react-firebase-hooks/auth";
    import { query, collection, getDocs, where } from "firebase/firestore";
    import "./Dashboard.css";
    import React, { useEffect, useState } from "react";
    import { useNavigate } from "react-router-dom";
    
    
    function Dashboard() {
      const [user, loading, error] = useAuthState(auth);
      const [name, setName] = useState("");
      const navigate = useNavigate();
      const fetchUserName = async () => {
        try {
          const q = query(collection(db, "users"), where("uid", "==", user?.uid));
          const doc = await getDocs(q);
          const data = doc.docs[0].data();
          setName(data.name);
        } catch (err) {
          console.error(err);
          alert("An error occured while fetching user data");
        }
      };
      useEffect(() => {
        if (loading) return;
        if (!user) return navigate("/");
        fetchUserName();
      }, [user, loading]);
      return (
        <div className="dashboard">
            <div className="dashboard__container">
            Logged in as
              <div>{name}</div>
              <div>{user?.email}</div>
              <button className="dashboard__btn" onClick={logout}>
              Logout
              </button>
            </div>
          </div>
      );
    }
    export default Dashboard;
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Playground
    • Snippets
    • Cookbooks
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.