Home > Net >  firebase is not connected to Reactjs
firebase is not connected to Reactjs

Time:10-13

i have built a project in reactjs and it needs auth so i was trying to connect it to firebase since it is the easier way

i have been following one toturial on youtube but his way wasnt working for me

here is my code:

the firebase-config code:

import { initializeApp } from "firebase/app";
import { getAuth, onAuthStateChanged } from "firebase/auth";
import firebase from "firebase/compat/app";
import "firebase/compat/auth";

// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
  apiKey: "AIzaSyBoKEW_g0gOwNKkHGMAyhXxC0ESfdsVhKI",
  authDomain: "kargoevi-auth.firebaseapp.com",
  projectId: "kargoevi-auth",
  storageBucket: "kargoevi-auth.appspot.com",
  messagingSenderId: "726037811463",
  appId: "1:726037811463:web:42d75c7f5c1d1b5b9bf5a2",
  measurementId: "G-PJXGLVZ6GQ",
};
const app = initializeApp(firebaseConfig);
export const auth = getAuth(app);

export default app;

the Auth code:

import React, { useState, useEffect } from "react";
import { onAuthStateChanged } from "firebase/auth";
import { auth } from "./base.js";

export const AuthContext = React.createContext();

export const AuthProvider = ({ children }) => {
  const [currentUser, setCurrentUser] = useState(null);
  const [pending, setPending] = useState(true);

  useEffect(() => {
    onAuthStateChanged(auth, (user) => {
      setCurrentUser(user);
      setPending(false);
    });
  }, []);
  if (pending) {
    return <>Loading...</>;
  }

  return (
    <AuthContext.Provider
      value={{
        currentUser,
      }}
    >
      {children}
    </AuthContext.Provider>
  );
};

the private route code:

import React, { useContext } from "react";
import { Route, Redirect } from "react-router-dom";
import { AuthContext } from "./Auth";

const PrivateRoute = ({ component: RouteComponent, ...rest }) => {
  const { currentUser } = useContext(AuthContext);
  return (
    <Route
      {...rest}
      render={(routeProps) =>
        !!currentUser ? (
          <RouteComponent {...routeProps} />
        ) : (
          <Redirect to={"/login"} />
        )
      }
    />
  );
};

export default PrivateRoute;

so my goal is to have an authentication while signing up and when logging in

here is the code for both sign up and log in

signup code :

import { createUserWithEmailAndPassword } from "firebase/auth";
import { auth } from "../auth/base.js";

const SignUp = ({ history }) => {
  const handleSignUp = useCallback(
    async (event) => {
      event.preventDefault();
      const { email, password } = event.target.elements;
      try {
        await createUserWithEmailAndPassword(auth, email.value, password.Value);
        console.log("test");
        history.Push("/");
      } catch (error) {
        alert(error);
      }
    },
    [history]
  );

 return (
         <form
         onSubmit={handleSignUp}

      >

so what I want is to see when someone is signing up in the firebase database also i want only registered ones to be able to log in now it not working

CodePudding user response:

The app that you are exporting is an instance of FirebaseApp and does not have a .auth() method. You seem to be following an old tutorial that uses the old namespaced version of Firebase SDK. Instead try removing the compat libraries and refactoring the code as shown below:

import { initializeApp } from "firebase/app";
import { getAuth, onAuthStateChanged } from "firebase/auth"; 

const firebaseConfig = {...};

const app = initializeApp(firebaseConfig);

// use this auth instance else where
export const auth = getAuth(app);

In the new modular SDK, createUserWithEmailAndPassword() is a top level function. Try:

import { auth } from "../path/to/base.js"
import { createUserWithEmailAndPassword } from "firebase/auth"

const handleSignUp = useCallback(
  async (event) => {
      event.preventDefault();
      const { email, password } = event.target.elements;
      try {
        await createUserWithEmailAndPassword(auth, email.value, password.Value);
        history.Push("/");
      } catch (error) {
        alert(error);
      }
    },
    [history]
);

Also checkout Getting started with Firebase Authentication on the web

  • Related