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:

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

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

const auth = firebaseObj.auth;

function App() {
  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 (
      <div className="md:flex min-h-screen">
        <div className="md:w-2/5 xl:w-4/5 p-6">
          <Signin />
        </div>
      </div>
    );
  } else {
    return (
      <FirebaseContext.Provider
        value={{
          firebase,
        }}
      >
        <div className="md:flex min-h-screen">
          <div className="md:w-2/5 xl:w-4/5 p-6">
            <Routes>
              <Route path="/" element={<Sidebar />} />
              <Route path="/sidebar" element={<Sidebar />} />
              <Route path="/ordenes" element={<Ordenes />} />
              <Route path="/menu" element={<Menu />} />
              <Route path="/nuevo-plato" element={<NuevoPlato />} />
            </Routes>
          </div>
        </div>
      </FirebaseContext.Provider>
    );
  }
}

export default App;

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?"