Home > Mobile >  React Function to Component and Setting State with Function Return
React Function to Component and Setting State with Function Return

Time:06-17

here's the jist of where I'm stuck (or just read the title for my question).

I have a firebase.js file where I have functions to authenticate. signinGithub, signinGoogle, signinEmail and so forth. The Firebase Auth business logic is in these functions.

I am showing errors with console.log or alert from these functions. The functions are imported into a Component and I don't know how to capture the functions result into the component by somehow setting state from this out-of-component function file.

Here's a basic example:

firebase.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}
...

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)
  render(
    {* Below is the method call from the imported custom firebase function *}
    <button onClick={signInWithGitHub}>
      Login with GitHub
    </button>
  )
} 
...

I was thinking something like this but I can't fully resolve it in my mind:

  • Set state in Login.js const [message, setMessage] = useState('')
  • When the imported signinWithGitHub has an error message --

I'm stuck figuring out how to apply to function message to the state, any ideas?

CodePudding user response:

You can create a custom function inside your Login. jsx file to call the original signInWithGitHub method with a try catch block. And more importantly, you should not use render inside a functional component. Use return to render the JSX in 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>}
    </>
  );
}
  • Related