skip to Main Content

What’s the easiest way of setup Authentication Context in ReactJs with Firebase Authentication functioanlities?

I want to setup Firebase Authentication in my ReactJs website along with that I want to use Context API in it. What’s the proper technique I should apply for this.

2

Answers


  1. import { getAuth, onAuthStateChanged } from "firebase/auth";
    import { useEffect, useState, createContext } from "react";
    
    const AuthContext = createContext();
    const auth = getAuth();
    
    function AuthProvider({ children }) {
        const [authUser, setAuthUser] = useState(undefined);
    
        useEffect(() => {
            return onAuthStateChanged(auth, user => setAuthUser(user));
        }, []);
    
        return <AuthContext.Provider value={authUser}>{children}</AuthContext.Provider>;
    }
    

    More details in this SO answer.

    Login or Signup to reply.
  2. Setting up Firebase Authentication with React involves several steps. Here’s a basic setup using the Firebase JavaScript SDK and React Context for managing the authentication state:

    Create an AuthContext for managing the authentication state:

    import React, { createContext, useEffect, useState } from 'react';
    import firebase from 'firebase/app';
    import 'firebase/auth';
    
    // Initialize Firebase with your config
    firebase.initializeApp(firebaseConfig);
    
    // Create AuthContext
    export const AuthContext = createContext();
    
    export const AuthProvider = ({ children }) => {
      const [currentUser, setCurrentUser] = useState(null);
    
      useEffect(() => {
        const unsubscribe = firebase.auth().onAuthStateChanged((user) => {
          setCurrentUser(user);
        });
    
        return () => {
          unsubscribe();
        };
      }, []);
    
      const signIn = async (email, password) => {
        try {
          await firebase.auth().signInWithEmailAndPassword(email, password);
        } catch (error) {
          console.error('Error signing in:', error);
        }
      };
    
      const signOut = async () => {
        try {
          await firebase.auth().signOut();
        } catch (error) {
          console.error('Error signing out:', error);
        }
      };
    
      const value = {
        currentUser,
        signIn,
        signOut,
      };
    
      return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
    };
    

    Wrap your app with AuthProvider:

    import React from 'react';
    import { AuthProvider } from './AuthContext';
    import YourApp from './YourApp'; // Replace this with your app component
    
    const App = () => {
      return (
        <AuthProvider>
          <YourApp />
        </AuthProvider>
      );
    };
    
    export default App;
    

    Use the AuthContext in your components:

    import React, { useContext } from 'react';
    import { AuthContext } from './AuthContext';
    
    const YourComponent = () => {
      const { currentUser, signIn, signOut } = useContext(AuthContext);
    
      // Use currentUser, signIn, signOut as needed
    
      return (
        <div>
          {currentUser ? (
            <button onClick={signOut}>Sign Out</button>
          ) : (
            <button onClick={() => signIn('email', 'password')}>Sign In</button>
          )}
        </div>
      );
    };
    
    export default YourComponent;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search