aquí está la idea de dónde estoy atascado (o simplemente lea el título de mi pregunta).
Tengo un archivo firebase.js donde tengo funciones para autenticar. signinGithub , signinGoogle , signinEmail y así sucesivamente. La lógica empresarial de Firebase Auth se encuentra en estas funciones.
Estoy mostrando errores con console.log o alert de estas funciones. Las funciones se importan a un Component y no sé cómo capturar el resultado de las funciones en el componente configurando de alguna manera el estado de este archivo de función fuera del componente.
He aquí un ejemplo básico:
base de fuego.js
... const signInWithGitHub = async () => { try { const res = await signInWithPopup(auth, githubProvider) const user = res.user } catch (err) { alert(err) // ** I want to pass "err" from here to Login // ** component by updating Logins state for a message } } export {signinWithGitHub} ...Iniciar sesión.jsx
import React, { useEffect, useState } from "react" import { useAuthState } from "react-firebase-hooks/auth" import { auth, signInWithGitHub } from "../lib/firebase" function Login() { const [user, loading, error] = useAuthState(auth) render( {* Below is the method call from the imported custom firebase function *} <button onClick={signInWithGitHub}> Login with GitHub </button> ) } ...Estaba pensando algo como esto, pero no puedo resolverlo completamente en mi mente:
const [message, setMessage] = useState('')error --Estoy atascado descifrando cómo aplicar al mensaje de función al estado, ¿alguna idea?
Puede crear una función personalizada dentro de su inicio de Login. jsx para llamar al método signInWithGitHub original con un bloque try catch . Y lo que es más importante, no debe usar render dentro de un componente funcional. Use return para renderizar el JSX en DOM.
firebase.js
export const signInWithGitHub = async () => { try { const res = await signInWithPopup(auth, githubProvider); const user = res.user; } catch (err) { throw new Error(err?.message || "Unable to sign in with GitHub"); } }; Login.jsx
import React, { useEffect, useState } from "react"; import { useAuthState } from "react-firebase-hooks/auth"; import { auth, signInWithGitHub } from "../lib/firebase"; function Login() { const [user, loading, error] = useAuthState(auth); const [errorMessage, setErrorMessage] = useState(""); const onLogin = async () => { try { await signInWithGitHub(); } catch (err) { setErrorMessage(err); } }; return ( <> <button onClick={onLogin}>Login with GitHub</button> {!!errorMessage && <h5>{errorMessage}</h5>} </> ); }