Home > Back-end >  problem with authentication in react with firebase
problem with authentication in react with firebase

Time:07-10

I have an application in react with firebase. It consists of a single component that would display the message "hola a todos". It works fine if I comment out this line in the Component.js file:const { logIn, googleSignIn } = useUserAuth(); But if I uncomment it it doesn't show the message "hello everyone" but it doesn't give any compilation errors either. These are the three files that the project consists of: And this is the link to the repository:link to repo

App.js:

import { Container, Row, Navbar,Col } from "react-bootstrap";
import "./App.css";
import Componente from "./components/Componente";

function App() {

  return (
    <>
    <Container style={{ width: "400px" }}>
      <Row>
        <Col>
          <Componente />
        </Col>
      </Row>
    </Container>
  </>
    
  );
}

export default App;

Componente.js:

mport React, { useState } from "react";
import { useUserAuth } from "../context/UserAuthContext";

const Componente = () => {
 
    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");
    const [error, setError] = useState("");
    //if i uncoment this line the app doesn't show the message
    //const { logIn, googleSignIn } = useUserAuth();


  return (
    <>
      <div>
        <h1>hola a todos</h1>
      </div>
      
    </>
  );
};

export default Componente;

UserAuthContext.js:

import { createContext, useContext, useEffect, useState } from "react";
import {
  createUserWithEmailAndPassword,
  signInWithEmailAndPassword,
  onAuthStateChanged,
  signOut,
  GoogleAuthProvider,
  signInWithPopup,
} from "firebase/auth";
import { auth } from "../firebase";

const userAuthContext = createContext();

export function UserAuthContextProvider({ children }) {
  const [user, setUser] = useState({});

  function logIn(email, password) {
    return signInWithEmailAndPassword(auth, email, password);
  }
  function signUp(email, password) {
    return createUserWithEmailAndPassword(auth, email, password);
  }
  function logOut() {
    return signOut(auth);
  }
  function googleSignIn() {
    const googleAuthProvider = new GoogleAuthProvider();
    return signInWithPopup(auth, googleAuthProvider);
  }

  useEffect(() => {
    const unsubscribe = onAuthStateChanged(auth, (currentuser) => {
      console.log("Auth", currentuser);
      setUser(currentuser);
    });

    return () => {
      unsubscribe();
    };
  }, []);

  return (
    <userAuthContext.Provider
      value={{ user, logIn, signUp, logOut, googleSignIn }}
    >
      {children}
    </userAuthContext.Provider>
  );
}

export function useUserAuth() {
  return useContext(userAuthContext);
}

CodePudding user response:

Did you forget to wrap your whole app or component with UserAuthContextProvider?

  • Related