How to make registration mandatory with Firebase auth in my React app?

Viewed 249

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. However, when I enter the email and password, the application does not move. The log works, because a consolelog() shows it to me

It's the second screenshot

I do not understand what I have wrong. Now I show the modified App.js file to show the form, but when I register, the application does not reach the Menu, page <Sidebar />

archivo App.js modificado

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
  }, [])

  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={<Signin />} />
            <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

enter image description here

enter image description here

I have created a web application with React (https://github.com/facebook/create-react-app. --- npx create-react-app my-app)

It is a simple application with three screens: Main, Menu, New Products The App that shows a list of products from a store, from where the user can add more products. Once finished, I have decided that registration by email is mandatory in order to see the content and be able to add products. I have added the appropriate configuration to get the login through Firebase, the application always starts directly, although it shows the registration form.

The configuration of App.js is correct, but I don't know how to make my application start from Signin, and once the email and user name were entered, I was sent to the application

I have tried several ways, and in all of them it starts the application directly. I have added Signin to App.js, but I need to see what App.js shows, it is necessary to enter the email and password. Now, there is the application menu

File App.js

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
  }, [])

  return (
    <FirebaseContext.Provider
      value={{
        firebase
      }}
    >
      <div className="md:flex min-h-screen" >
        <Sidebar />

        <div className="md:w-2/5 xl:w-4/5 p-6">
          <Routes>
            <Route path="/" element={<Ordenes />} />
            <Route path="/menu" element={<Menu />} />
            <Route path="/nuevo-producto" element={<NuevoProducto />} />
          </Routes>

        </div>

      </div>

    </FirebaseContext.Provider>
  )
}

export default App

File Signin.js

import React, { useRef } from 'react'
//import { auth } from '../firebase'
import firebaseObj from '../firebase/firebase'

const auth = firebaseObj.auth

const Signin = () => {
    const emailRef = useRef(null);
    const passwordRef = useRef(null);
    const signUp = e => {
        e.preventDefault();
        auth.createUserWithEmailAndPassword(
            emailRef.current.value,
            passwordRef.current.value
        ).then(user => {
            console.log(user)
        }).catch(err => {
            console.log(err)
        })
    }
    const signIn = e => {
        e.preventDefault();
        auth.signInWithEmailAndPassword(
            emailRef.current.value,
            passwordRef.current.value
        ).then(user => {
            console.log(user)
        }).catch(err => {
            console.log(err)
        })
    }
    return (
        <div className="mb-4">
            <form action="">
                <h1>Sign in</h1>
                <input
                className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
                ref={emailRef} type="email" placeholder="email"/>
                <input 
                className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
                ref={passwordRef} type="password" />
                <button onClick={signIn}>Sign in </button>
            </form>
        </div>
    )
}

export default Signin
1 Answers

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.

Related