Firebase API is not working for me. I am trying to do login/sign up


Hello,

the dashboard on my site (coded using react) is not loading as the firebase sign in/sign up api seems to not be working. I have included screenshot of errors I see in the console on browser.

I’ve tried everything including chatgpt. But, i am stuck and I am usually just front-end (but I do more UX/UI work now) so this backend stuff is confusing me. (Please ignore that there is no styling. i wanted to get the backend/API stuff out of the way first).

Problem- when logging in it says user not found. The dashboard also does not load.

//dashboard
import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { doc, getDoc, collection, query, where, getDocs } from 'firebase/firestore';
import { onAuthStateChanged } from 'firebase/auth';
import { db, auth } from '../firebase/config';
import { Card, CardHeader, CardContent } from '../components/UI/card';
import { Progress } from '../components/UI/progress';
import { Button } from '../components/UI/button';
import { Bookmark, CheckCircle2, Loader2 } from 'lucide-react';

// Motivational quotes for the dashboard
const motivationalQuotes = [
  "Every application is a step towards your dream job.",
  "Your perfect role is out there, waiting for you to find it.",
  "Success is the sum of small efforts repeated day in and day out.",
  "The only way to do great work is to love what you do. Keep searching until you find it.",
  "Your career journey is unique. Embrace every twist and turn.",
];

export default function Dashboard() {
  const [userProfile, setUserProfile] = useState(null);
  const [applications, setApplications] = useState([]);
  const [savedJobs, setSavedJobs] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const navigate = useNavigate();

  useEffect(() => {
    // Firebase auth listener
    const unsubscribe = onAuthStateChanged(auth, (user) => {
      if (user) {
        if (db) {
          fetchUserData(user); // Fetch data if user is authenticated
        } else {
          setError("Firebase not initialized properly");
          setLoading(false);
        }
      } else {
        setLoading(false);
        setUserProfile(null);
      }
    });

    return () => unsubscribe();
  }, []);

  // Fetch user data and job applications
  async function fetchUserData(user, retryCount = 0) {
    try {
      setLoading(true);
      console.log("Fetching user document...");
      
      const userDoc = await getDoc(doc(db, 'users', user.uid));
      
      if (userDoc.exists()) {
        console.log("User document found:", userDoc.data());
        setUserProfile(userDoc.data());

        // Fetch job applications
        const applicationsQuery = query(collection(db, 'applications'), where('userId', '==', user.uid));
        const applicationsSnapshot = await getDocs(applicationsQuery);
        setApplications(applicationsSnapshot.docs.map(doc => ({ id: doc.id, ...doc.data() })));

        // Fetch saved jobs
        const savedJobsQuery = query(collection(db, 'savedJobs'), where('userId', '==', user.uid));
        const savedJobsSnapshot = await getDocs(savedJobsQuery);
        setSavedJobs(savedJobsSnapshot.docs.map(doc => ({ id: doc.id, ...doc.data() })));

      } else {
        console.log("No user document found!");
        setError("User profile not found");
      }
    } catch (err) {
      console.error('Error fetching user data:', err);
      if (retryCount < 3) {
        console.log(`Retrying... Attempt ${retryCount + 1}`);
        await new Promise(resolve => setTimeout(resolve, 1000)); // Wait 1 second
        return fetchUserData(user, retryCount + 1);
      }
      setError(`Failed to load dashboard data: ${err.message}`);
    } finally {
      setLoading(false);
    }
  }

  // If data is loading, display a loading spinner
  if (loading) {
    return (
      <div className="flex justify-center items-center h-64">
        <Loader2 className="h-8 w-8 animate-spin text-primary-500" />
      </div>
    );
  }

  // If there's an error, display the error message
  if (error) {
    return (
      <div className="text-secondary-500 text-center">
        {error}
        <Button onClick={() => navigate('/login')} className="mt-4">Back to Login</Button>
      </div>
    );
  }

  // If the user profile is not available, prompt the user to log in
  if (!userProfile) {
    return (
      <div className="text-center">
        <p>Please log in to view your dashboard.</p>
        <Button onClick={() => navigate('/Login')} className="mt-4">Log In</Button>
      </div>
    );
  }

  // Calculate progress towards weekly application goal
  const weeklyGoal = userProfile.weeklyGoal || 5;
  const appliedThisWeek = applications.filter(app => {
    const appDate = new Date(app.appliedAt || 0); // Safely handle undefined dates
    const weekAgo = new Date();
    weekAgo.setDate(weekAgo.getDate() - 7);
    return appDate > weekAgo;
  }).length;

  const progress = (appliedThisWeek / weeklyGoal) * 100;
  const randomQuote = motivationalQuotes[Math.floor(Math.random() * motivationalQuotes.length)];

  return (
    <div className="space-y-6">
      <h1 className="text-3xl font-bold text-primary-700">Welcome back, {userProfile.displayName || 'Jobseeker'}!</h1>
      
      <Card>
        <CardHeader>
          <h2 className="text-xl font-semibold text-primary-600">Your Weekly Journey</h2>
        </CardHeader>
        <CardContent>
          <div className="space-y-2">
            <div className="flex justify-between items-center text-sm font-medium text-neutral-600">
              <span>{appliedThisWeek} of {weeklyGoal} applications this week</span>
              <span>{Math.round(progress)}%</span>
            </div>
            <Progress value={progress} className="w-full" />
          </div>
        </CardContent>
      </Card>

      <div className="grid md:grid-cols-2 gap-6">
        <Card>
          <CardContent className="pt-6">
            <div className="flex items-center justify-between">
              <div className="flex items-center space-x-2">
                <CheckCircle2 className="h-5 w-5 text-primary-500" />
                <span className="text-lg font-medium text-neutral-700">Applications Sent</span>
              </div>
              <span className="text-2xl font-bold text-primary-500">{applications.length}</span>
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="pt-6">
            <div className="flex items-center justify-between">
              <div className="flex items-center space-x-2">
                <Bookmark className="h-5 w-5 text-secondary-500" />
                <span className="text-lg font-medium text-neutral-700">Saved Opportunities</span>
              </div>
              <span className="text-2xl font-bold text-secondary-500">{savedJobs.length}</span>
            </div>
          </CardContent>
        </Card>
      </div>

      <Card>
        <CardContent className="py-6">
          <blockquote className="text-lg italic text-center text-primary-600">
            "{randomQuote}"
          </blockquote>
        </CardContent>
      </Card>

      <div className="flex space-x-4">
        <Button className="flex-1" onClick={() => navigate('/jobs')}>Discover Opportunities</Button>
        <Button variant="outline" className="flex-1" onClick={() => navigate('/progress')}>
          View Your Progress
        </Button>
      </div>
    </div>
  );
}

this is config

import { initializeApp } from 'firebase/app';
import { getAuth } from 'firebase/auth';
import { getFirestore } from 'firebase/firestore';

const firebaseConfig = {
    apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
    authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
    projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
    storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
    messagingSenderId: process.env.REACT_APP_FIREBASE_MESSAGING_SENDER_ID,
    appId: process.env.REACT_APP_FIREBASE_APP_ID
  };


const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const db = getFirestore(app);

console.log('Firebase initialized:', !!app);
console.log('Auth initialized:', !!auth);
console.log('Firestore initialized:', !!db);

export { auth, db };

this is authcontext

import { createContext, useContext, useState, useEffect } from 'react';
import { auth } from '../firebase/config';
import { onAuthStateChanged } from 'firebase/auth';
import { signIn, signUp, logOut, signInWithGoogle } from '../firebase/auth';  // Correct imports here

const AuthContext = createContext();

export function AuthProvider({ children }) {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const unsubscribe = onAuthStateChanged(auth, (user) => {
      console.log('Auth state changed:', user ? 'User logged in' : 'User logged out');
      setUser(user);
      setLoading(false);
    });
  
    return unsubscribe;
  }, []);

  const value = {
    user,
    login: signIn,  // Ensure you use the correct signIn
    signup: signUp,  // Ensure you use the correct signUp
    logout: logOut,  // Ensure you use the correct logOut
    signInWithGoogle,  // Ensure you use the correct Google SignIn
  };

  return (
    <AuthContext.Provider value={value}>
      {!loading && children}
    </AuthContext.Provider>
  );
}

export function useAuth() {
  return useContext(AuthContext);
}

this is auth

import { getAuth, signInWithEmailAndPassword, createUserWithEmailAndPassword, signOut, signInWithPopup, GoogleAuthProvider } from 'firebase/auth';
import { auth } from './config';  // Make sure auth is initialized in config

// Sign in function with Email and Password
export const signIn = async (email, password) => {
  try {
    const userCredential = await signInWithEmailAndPassword(auth, email, password);
    return userCredential.user;
  } catch (error) {
    console.error("Error signing in with email:", error);
    throw error;
  }
};

// Sign up function with Email and Password
export const signUp = async (email, password) => {
  try {
    const userCredential = await createUserWithEmailAndPassword(auth, email, password);
    return userCredential.user;
  } catch (error) {
    console.error("Error signing up with email:", error);
    throw error;
  }
};

// Log out function
export const logOut = async () => {
  try {
    await signOut(auth);
    console.log("User logged out successfully.");
  } catch (error) {
    console.error("Error logging out:", error);
    throw error;
  }
};

// Sign in with Google
export const signInWithGoogle = async () => {
  const provider = new GoogleAuthProvider();
  try {
    const result = await signInWithPopup(auth, provider);
    return result.user;
  } catch (error) {
    console.error("Error signing in with Google:", error);
    throw error;
  }
};

Thank you. All help and feedback is appreciated.

hello and welcome back to fcc forum :slight_smile:

it seems (from screenshot) user auth state is “changing” from logout to logged in and vice versa!! sounds like a good start to me!!

have you checked out there docs yet? in my opinion its very well documented, give it a go if you havent already, happy reading :slight_smile: Fundamentals  |  Firebase Documentation