0

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

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

12 Comments

dont i need to export the app in the config?
@Dharamaraj also is it the same method for the log in?
@HazalKaya you don't generally, and for login there is a different function called signInWithEmailAndPassword(). Do refer to the linked video.
ok i was trying since yesterday but it doesnt work would u please edit ur answer by adding login?
@HazalKaya the "login" sounds likes a totally different issue and we don't even know what you have tried or what error do you get. If it's totally unrelated to original issues, it might be best to post a new question and mark this one as answered or at least update the current one with more details .
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.