Skip to content Skip to sidebar Skip to footer

How To Make Registration Mandatory With Firebase Auth In My React App?

EDIT TO ADD DETAILS The application must be started with a page with a form, enter email and password and when Login takes us to the menu screen, which I show in the screenshot. Ho

Solution 1:

The reason you don't get to the SignIn page after you register is that there is no logic for it. If you make just a simple if statament like here it should work:

importReact, { useState, useEffect } from"react";
import { Routes, Route } from"react-router";

import firebase, { FirebaseContext } from"./firebase";
//import { auth } from 'firebase'import firebaseObj from"./firebase";
importOrdenesfrom"./components/paginas/Ordenes";
importMenufrom"./components/paginas/Menu";
importNuevoPlatofrom"./components/paginas/NuevoPlato";
importSidebarfrom"./components/ui/Sidebar";
importSigninfrom"./components/Signin";

const auth = firebaseObj.auth;

functionApp() {
  const [user, setUser] = useState(null);
  useEffect(() => {
    const unsubscribe = auth.onAuthStateChanged((userAuth) => {
      const user = {
        uid: userAuth?.uid,
        email: userAuth?.email,
      };
      if (userAuth) {
        console.log(userAuth);
        setUser(user);
      } else {
        setUser(null);
      }
    });
    return unsubscribe;
  }, []);

  if (!user) {
    return (
      <divclassName="md:flex min-h-screen"><divclassName="md:w-2/5 xl:w-4/5 p-6"><Signin /></div></div>
    );
  } else {
    return (
      <FirebaseContext.Providervalue={{firebase,
        }}
      ><divclassName="md:flex min-h-screen"><divclassName="md:w-2/5 xl:w-4/5 p-6"><Routes><Routepath="/"element={<Sidebar />} />
              <Routepath="/sidebar"element={<Sidebar />} />
              <Routepath="/ordenes"element={<Ordenes />} />
              <Routepath="/menu"element={<Menu />} />
              <Routepath="/nuevo-plato"element={<NuevoPlato />} />
            </Routes></div></div></FirebaseContext.Provider>
    );
  }
}

exportdefaultApp;

That is just for example purpose. I would recommend to put the auth state listener into a Provider and create custom routes that automaticaly reroute to the SignIn page if no user is logged in.

Here you have an example of such an Provider that I use in every of my projects.

An here is an example of those custom routes that are listening to that provier.

Post a Comment for "How To Make Registration Mandatory With Firebase Auth In My React App?"