I moved the firebase auth to a useContext components. The only thing i am trying to figure out is how to reference the async GoogleLogin function from the useContext to the button (onClick event) on the Login page.
That's my UserContext file
import { signInWithPopup, GoogleAuthProvider } from 'firebase/auth';
import { auth } from '../utils/firebase';
import { useAuthState } from 'react-firebase-hooks/auth';
import { createContext } from 'react';
import { useRouter } from 'next/router';
const UserContext = createContext(null);
export const UserProvider = ({ children}) => {
const route = useRouter();
const [user, loading] = useAuthState(auth);
const googleProvider = new GoogleAuthProvider();
const GoogleLogin = async () => {
try {
const result = await signInWithPopup(auth, googleProvider);
} catch (error) {
console.log(error);
}
};
return <UserContext.Provider value={user}>{children}</UserContext.Provider>;
};
export default UserContext;
That's my Login component
import UserContext from '../../components/UserContext';
import {useContext } from 'react';
import { FcGoogle } from 'react-icons/fc';
const Login = () => {
const user = useContext(UserContext);
return (
<div className='shadow-xl mt-32 p-10 text-gray-700'>
<h2 className='text-2xl font-medium'>Join Today</h2>
<div className='py-4'>
<h3 className='py-4'>Sign in with one of the providers</h3>
<button
onClick={GoogleLogin}
className='text-white bg-gray-700 w-full font-medium rounded-lg flex align-middle p-4 gap-2'>
<FcGoogle className='text-2xl'></FcGoogle> Sign in with Google
</button>
</div>
</div>
);
};
export default Login;
CodePudding user response:
you can pass UserContext.Provider value
to an object like
UserContext file
// other code
<UserContext.Provider value={{user, GoogleLogin}}>{children}</UserContext.Provider>;
// rest of the code
Login component
// other code
const {user, GoogleLogin} = useContext(UserContext);
// rest of your code
read more in new beta react documentation here