Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 8383

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 60k
Author
Asked: November 28, 20242024-11-28T12:35:07+00:00 2024-11-28T12:35:07+00:00

FireBase Authentication – wds

  • 60k

Folder Structure

Output Image

App.js Code

import Dashboard from "./Components/Dashboard"; import Login from "./Components/Login"; import PrivateRoute from "./Components/PrivateRoute"; import Signup from "./Components/Signup"; import { BrowserRouter, Routes, Route, Navigate } from "react-router-dom";   function App() {    return (     < >       <BrowserRouter>         <Routes>           <Route path="/" element={<PrivateRoute>  <Dashboard name='aksh' /> </PrivateRoute>} />           <Route path="/signup" element={<Signup />} />           <Route path="/login" element={<Login />} />           <Route path="*" element={<h1> Error: 404 Not Found </h1>} />         </Routes>       </BrowserRouter>      </>   ); }  export default App;  
Enter fullscreen mode Exit fullscreen mode

Dashboard.js Code

import React from 'react' import { useAuth } from '../Context/AuthContext'; import { Link, useNavigate } from 'react-router-dom';   const Dashboard = (props) => {   const { currentUser, signout } = useAuth();   const navigate = useNavigate();    console.log('props', props);    async function handleClick() {     try {       await signout();       // navigate('/login')     } catch (error) {       console.log('error', error)     }   }    return (     <>        <h3> DashBoard  </h3>       <p>         Name - {currentUser && currentUser.email}       </p>        <Link className='btn btn-primary w-100' to='update-profile'>Update Profile</Link>       <button className="btn-primary" onClick={handleClick}>Logout</button>     </>   ) }  export default Dashboard  
Enter fullscreen mode Exit fullscreen mode

Login.js Code

import { useState, useRef } from 'react' import { useAuth } from '../Context/AuthContext'; import { NavLink, useNavigate } from 'react-router-dom';  const Login = () => {     const emailRef = useRef();     const passwordRef = useRef();      const [error, setError] = useState('');     const [loading, setLoading] = useState(false);      const { login, currentUser } = useAuth();     const navigate = useNavigate();      async function handleSubmit(e) {         e.preventDefault();          try {             setLoading(true);             setError('');             await login(emailRef.current.value, passwordRef.current.value);             navigate('/');         } catch (e) {             setError(`${e.message}`)         }          setLoading(false);     }     return (         <div className="row d-flex justify-content-center vh-100 align-items-center">             <div className="col-md-6  mx-auto bg-dark text-light">                 {currentUser && currentUser.email}                 {error === '' ? null : <h6 className="alert alert-danger"> {error}  </h6>}                  <form onSubmit={handleSubmit}>                     <h1 className="text-center"> Sign Up </h1>                     <div className="mb-3">                         <label htmlFor="email" className="form-label">Email address</label>                         <input type="email" className="form-control" id="email" ref={emailRef} aria-describedby="emailHelp" />                      </div>                     <div className="mb-3">                         <label htmlFor="password" className="form-label">Password</label>                         <input type="password" className="form-control" ref={passwordRef} id="password" />                     </div>                      <button type="submit" disabled={loading} className="btn btn-primary"> {loading ? "Loading" : "Login"} </button>                      <br />                     <NavLink to='/signup' className="text-white">Don't have an account? Signup Here </NavLink>                 </form>             </div>          </div>     ) }  export default Login;  
Enter fullscreen mode Exit fullscreen mode

PrivateRoute.js

import React from 'react' import { Navigate, Route } from 'react-router-dom' import { useAuth } from '../Context/AuthContext';   export default function PrivateRoute({ children }) {     const { currentUser } = useAuth();     console.log('rest', children);     return (         currentUser ? children : <Navigate to='/login' />     ) }  
Enter fullscreen mode Exit fullscreen mode

Signup.js Code

import { useState, useRef } from 'react' import { useAuth } from '../Context/AuthContext'; import { NavLink, useNavigate, useLoaderData} from 'react-router-dom';   const Signup = () => {   const emailRef = useRef();   const passwordRef = useRef();   const passwordConfirmRef = useRef();    const [error, setError] = useState('');   const [loading, setLoading] = useState(false);    const { signup, currentUser } = useAuth();    const navigate = useNavigate();    async function handleSubmit(e) {     e.preventDefault();      if (passwordRef.current.value !== passwordConfirmRef.current.value) {       return setError('Password do not Match.');     }      try {       setLoading(true);       setError('');       await signup(emailRef.current.value, passwordRef.current.value);       navigate('/');     } catch (e) {       setError(`${e.message}`)     }      setLoading(false);   }   return (      <div className="row d-flex justify-content-center vh-100 align-items-center">       <div className="col-md-6  mx-auto bg-dark text-light">         {currentUser && currentUser.email}         {error === '' ? null : <h6 className="alert alert-danger"> {error}  </h6>}          <form onSubmit={handleSubmit}>           <h1 className="text-center"> Sign Up </h1>           <div className="mb-3">             <label htmlFor="email" className="form-label">Email address</label>             <input type="email" className="form-control" id="email" ref={emailRef} aria-describedby="emailHelp" />             <div id="emailHelp" className="form-text text-white">We'll never share your email with anyone else.</div>           </div>           <div className="mb-3">             <label htmlFor="password" className="form-label">Password</label>             <input type="password" className="form-control" ref={passwordRef} id="password" />           </div>           <div className="mb-3">             <label htmlFor="confirm-password" className="form-label">Password Confirm</label>             <input type="password" className="form-control" ref={passwordConfirmRef} id="confirm-password" />           </div>            <button type="submit" disabled={loading} className="btn btn-primary"> {loading ? "Loading" : "Submit"} </button>            <br />           <NavLink to='/login' className="text-white">Already have an account? Login Here </NavLink>         </form>       </div>      </div>   ) }  export default Signup;  
Enter fullscreen mode Exit fullscreen mode

firebase-config.js Code

 import { getFirestore } from "firebase/firestore"; import { getAuth } from "firebase/auth"; // Import the functions you need from the SDKs you need import { initializeApp } from "firebase/app"; // TODO: Add SDKs for Firebase products that you want to use // https://firebase.google.com/docs/web/setup#available-libraries  // Your web app's Firebase configuration const firebaseConfig = {     apiKey: "",     authDomain: "",     projectId: "",     storageBucket: "",     messagingSenderId: "",     appId: "" };  // Initialize Firebase const app = initializeApp(firebaseConfig);  const db = getFirestore(app); const auth = getAuth(app);  export default db; export { auth }; 
Enter fullscreen mode Exit fullscreen mode

AuthContext.js Code

import React, { useContext, useState, useEffect } from 'react' import { createUserWithEmailAndPassword, signInWithEmailAndPassword, signOut} from "firebase/auth"; import { auth } from '../config/firebase-config';   const AuthContext = React.createContext();  const useAuth = () => {     return useContext(AuthContext); };  const AuthProvider = ({ children }) => {     const [currentUser, setCurrentUser] = useState();     const [loading, setLoading] = useState(true);      function signup(email, password) {         return createUserWithEmailAndPassword(auth, email, password)     }      function login(email, password) {         return signInWithEmailAndPassword(auth, email, password)     }      function signout() {         return signOut(auth)     }      useEffect(() => {         const unSubscribe = auth.onAuthStateChanged((user) => {             setCurrentUser(user);             setLoading(false);         });          return unSubscribe;     }, [])      const value = {         currentUser,         signup,         login,         signout     };     return (         <AuthContext.Provider value={value}>             {!loading && children}         </AuthContext.Provider>     ) };  export default AuthContext;  export { useAuth, AuthProvider };  
Enter fullscreen mode Exit fullscreen mode

Output 1

Output 2

Thank You.
You can follow us on:
Instagram for full stack web Development

beginnersjavascriptreactwebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 1k
  • Popular
  • Answers
  • Author

    How to ensure that all the routes on my Symfony ...

    • 0 Answers
  • Author

    Insights into Forms in Flask

    • 0 Answers
  • Author

    Kick Start Your Next Project With Holo Theme

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.