I have created an react project, here is the code:-
navbar.jsx:-
import React from 'react';
import { Link } from 'react-router-dom';
import { UserAuth } from '../context/AuthContext';
const Navbar = ({ url, text }) => {
const { user, logOut } = UserAuth();
const handleSignOut = async () => {
try {
await logOut()
} catch (error) {
console.log(error)
}
}
return (
<div className='flex justify-between bg-gray-200 p-4'>
<h1 className='text-center text-2xl font-bold'>
Firebase Google Auth & Context
</h1>
{user?.displayName ? (
<button onClick={handleSignOut}>Logout</button>
) : (
<Link to={url}>{text}</Link>
)}
</div>
);
};
export default Navbar;
Protected.js:-
import React from 'react';
import { Navigate } from 'react-router-dom';
import { UserAuth } from '../context/AuthContext';
const Protected = ({ children }) => {
const { user } = UserAuth();
if (!user) {
return <Navigate to='/' />;
}
return children;
};
export default Protected;
AuthContext.js:-
import { useContext, createContext, useEffect, useState } from 'react';
import {
GoogleAuthProvider,
signInWithPopup,
signInWithRedirect,
signOut,
onAuthStateChanged,
} from 'firebase/auth';
import { auth, databaseRef } from '../firebase';
const AuthContext = createContext();
export const AuthContextProvider = ({ children }) => {
const [user, setUser] = useState({});
const googleSignIn = () => {
const provider = new GoogleAuthProvider();
signInWithRedirect(auth, provider); // Choose your preferred sign-in method
};
const logOut = async () => { // Make logOut async for potential errors
try {
await signOut(auth);
} catch (error) {
console.error('Error signing out:', error);
}
};
useEffect(() => {
const unsubscribe = onAuthStateChanged(auth, (currentUser) => {
setUser(currentUser);
console.log('User', currentUser);
});
return unsubscribe;
}, []);
return (
<AuthContext.Provider value={{ googleSignIn, logOut, user, databaseRef }}>
{children}
</AuthContext.Provider>
);
};
export const UserAuth = () => {
return useContext(AuthContext);
};
Account.jsx:-
import React, { useEffect, useState } from 'react';
import { UserAuth } from '../context/AuthContext';
import Navbar from '../components/Navbar';
const Account = () => {
const { user, databaseRef } = UserAuth();
const [userIds, setUserIds] = useState([]);
useEffect(() => {
const fetchUserIds = async () => {
const snapshot = await databaseRef.child('userids').once('value');
const data = snapshot.val();
setUserIds(Object.values(data || {}));
};
fetchUserIds();
}, []);
return (
<div className='container'>
<Navbar url='/signin' text='Log out' />
<div className='w-[300px] m-auto'>
<h1 className='text-center text-2xl font-bold pt-12'>Account</h1>
<div>
<p>Welcome, {user?.displayName}</p>
{userIds.length > 0 && (
<ul>
{userIds.map((id) => (
<li key={id}>{id}</li>
))}
</ul>
)}
</div>
</div>
</div>
);
};
export default Account;
Home.jsx:-
import React from 'react'
import Navbar from '../components/Navbar'
const Home = () => {
return (
<div>
<Navbar url='/signin' text='Sign in' />
<h1 className='text-center text-3xl font-bold py-8'>Home Page</h1>
</div>
)
}
export default Home
Signin.jsx:-
import React, { useEffect } from 'react';
import { GoogleButton } from 'react-google-button';
import { UserAuth } from '../context/AuthContext';
import { useNavigate } from 'react-router-dom';
import Navbar from '../components/Navbar';
const Signin = () => {
const { googleSignIn, user, databaseRef } = UserAuth();
const navigate = useNavigate();
const handleGoogleSignIn = async () => {
try {
const result = await googleSignIn();
const userObj = result.user;
const userId = userObj.uid;
console.log('Attempting to save user ID:', userId); // Log before saving
await databaseRef.child('userids').push(userId);
console.log('User ID saved successfully:', userId);
navigate('/account');
} catch (error) {
console.error('Error during sign-in or saving user ID:', error);
}
};
useEffect(() => {
if (user != null) {
// navigate('/account');
}
}, [user]);
return (
<div>
<Navbar url='/' text='Home' />
<h1 className='text-center text-3xl font-bold py-8'>Sign in</h1>
<div className='max-w-[240px] m-auto py-4'>
<GoogleButton onClick={handleGoogleSignIn} />
</div>
</div>
);
};
export default Signin;
App.js:-
import React from 'react';
import { Route, Routes } from 'react-router-dom';
import Navbar from './components/Navbar';
import Protected from './components/Protected';
import { AuthContextProvider } from './context/AuthContext';
import Account from './pages/Account';
import Home from './pages/Home';
import Signin from './pages/Signin';
import { auth, db, databaseRef } from './firebase';
function App() {
return (
<div>
<AuthContextProvider>
<Routes>
<Route path='/' element={<Home />} />
<Route path='/signin' element={<Signin />} />
<Route
path='/account'
element={
<Protected>
<Account />
</Protected>
}
/>
</Routes>
</AuthContextProvider>
</div>
);
}
export default App;
firebase.js:-
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
import { getDatabase, ref } from 'firebase/database';
// TODO: Add SDKs for Firebase products that you want to use
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "QIazSyDO132QtFu798QoI472h6pb2KzdXZExyQs",
authDomain: "trail-24.firebaseapp.com",
databaseURL: "https://trail-24-default-rtdb.firebaseio.com",
projectId: "trail-24",
storageBucket: "trail-24.appspot.com",
messagingSenderId: "1011673947249",
appId: "1:1011943747984:web:08ee8dd634ffe87c55f915",
measurementId: "G-FSXIJTC9PX"
};
const app = initializeApp(firebaseConfig);
export const auth = getAuth(app);
const db = getDatabase(app);
export const databaseRef = ref(db);
This is the console log:-
User null
Signin.jsx:23 Error during sign-in or saving user ID: TypeError: Cannot read properties of undefined (reading 'user')
at Object.handleGoogleSignIn [as onClick] (Signin.jsx:14:1)
handleGoogleSignIn @ Signin.jsx:23
await in handleGoogleSignIn (async)
(anonymous) @ GoogleButton.js:108
callCallback @ react-dom.development.js:4161
invokeGuardedCallbackDev @ react-dom.development.js:4210
invokeGuardedCallback @ react-dom.development.js:4274
invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:4288
executeDispatch @ react-dom.development.js:9038
processDispatchQueueItemsInOrder @ react-dom.development.js:9070
processDispatchQueue @ react-dom.development.js:9083
dispatchEventsForPlugins @ react-dom.development.js:9094
(anonymous) @ react-dom.development.js:9285
batchedUpdates$1 @ react-dom.development.js:26096
batchedUpdates @ react-dom.development.js:3988
dispatchEventForPluginEventSystem @ react-dom.development.js:9284
dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay @ react-dom.development.js:6462
dispatchEvent @ react-dom.development.js:6454
dispatchDiscreteEvent @ react-dom.development.js:6427
Show 16 more frames
Show less
Navigated to https://trails-22.firebaseapp.com/__/auth/handler?apiKey=QIazSyDO132QtFu798QoI472h6pb2KzdXZExyQs&appName=%5BDEFAULT%5D&authType=signInViaRedirect&redirectUrl=http%3A%2F%2Flocalhost%3A3000%2Fsignin&v=9.6.11&providerId=google.com&scopes=profile
api.js?onload=__iframefcb691612:10
GET https://trails-22.firebaseapp.com/__/firebase/init.json 404 (Not Found)
Hj.send @ iframe_form_check.js:259
(anonymous) @ iframe_form_check.js:556
K @ iframe_form_check.js:170
es.zf @ iframe_form_check.js:556
fs @ iframe_form_check.js:557
g @ iframe_form_check.js:625
(anonymous) @ iframe_form_check.js:626
a @ iframe_form_check.js:168
(anonymous) @ iframe_form_check.js:168
c @ iframe_form_check.js:168
e.kc @ iframe_form_check.js:176
jh @ iframe_form_check.js:179
fh @ iframe_form_check.js:179
K.jk @ iframe_form_check.js:178
a @ iframe_form_check.js:168
(anonymous) @ iframe_form_check.js:168
c @ iframe_form_check.js:168
Qg @ iframe_form_check.js:169
a (async)
Jg @ iframe_form_check.js:169
bh @ iframe_form_check.js:175
K.then @ iframe_form_check.js:173
(anonymous) @ iframe_form_check.js:626
a @ iframe_form_check.js:168
(anonymous) @ iframe_form_check.js:168
c @ iframe_form_check.js:168
e.kc @ iframe_form_check.js:176
jh @ iframe_form_check.js:179
fh @ iframe_form_check.js:179
K.jk @ iframe_form_check.js:178
a @ iframe_form_check.js:168
(anonymous) @ iframe_form_check.js:168
c @ iframe_form_check.js:168
Qg @ iframe_form_check.js:169
a (async)
Jg @ iframe_form_check.js:169
bh @ iframe_form_check.js:175
K.then @ iframe_form_check.js:173
mt.qb @ iframe_form_check.js:624
mt.start @ iframe_form_check.js:623
(anonymous) @ iframe_form_check.js:634
(anonymous) @ api.js?onload=__iframefcb691612:10
Show 39 more frames
Show less
Navigated to https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=1011938947984-ohu9p7u73ihdqvhi2sr9d3t2tl42kmun.apps.googleusercontent.com&redirect_uri=https%3A%2F%2Ftrails-22.firebaseapp.com%2F__%2Fauth%2Fhandler&state=AMbdmDmFH3jre6VTr-qc6HyTkYZWC-zz_CJ_zn4EyBZGd28mJ8oz-flM3tRm1_PRn5AaC3Envhmv_42vjhuQo9cIny82ZDkvYUSoZszyYDWQOHN_ZkLH-faQ6PpZ-1Gefbzh4LinwHTFCM3Gov_WyGhG8kl7ayy5NKxMkPMUJnqV7lQ0QRXaaalTAgNUWvUscZJdRVOLPF82SaIFyh3uHBAvoUCpHmyed5P-vFCBq5iEeuWRP_eGAInDJikjawyUQZFWnnOgVUst4c7NHeLi_iy0VRhrLcBXchEjhdjoGTh2yeidWIiUaaYX6QJnBQK3ENLwoTsXhl3nfdX1aw&scope=openid%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email%20profile&context_uri=http%3A%2F%2Flocalhost%3A3000
5Third-party cookie will be blocked. Learn more in the Issues tab.
Navigated to https://trails-22.firebaseapp.com/__/auth/handler?state=AMbdmDmFH3jre6VTr-qc6HyTkYZWC-zz_CJ_zn4EyBZGd28mJ8oz-flM3tRm1_PRn5AaC3Envhmv_42vjhuQo9cIny82ZDkvYUSoZszyYDWQOHN_ZkLH-faQ6PpZ-1Gefbzh4LinwHTFCM3Gov_WyGhG8kl7ayy5NKxMkPMUJnqV7lQ0QRXaaalTAgNUWvUscZJdRVOLPF82SaIFyh3uHBAvoUCpHmyed5P-vFCBq5iEeuWRP_eGAInDJikjawyUQZFWnnOgVUst4c7NHeLi_iy0VRhrLcBXchEjhdjoGTh2yeidWIiUaaYX6QJnBQK3ENLwoTsXhl3nfdX1aw&code=4%2F0AeaYSHC6o8WykWTv1DWN0O83Bwd7QZcWw6nYM_ruo_ATobQYvk4RjthTfBhKL6XAfomKsA&scope=email+profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile+openid&authuser=2&prompt=none
Navigated to http://localhost:3000/signin
react refresh:6 Download the React DevTools for a better development experience: https://reactjs.org/link/react-devtools
6Third-party cookie will be blocked. Learn more in the Issues tab.
AuthContext.js:32 User UserImpl {providerId: 'firebase', proactiveRefresh: ProactiveRefresh, reloadUserInfo: {…}, reloadListener: null, uid: 'RdMQaBouH4RY5rVozaw7o9dSAro1', …}
Firebase Database rules:-
{
"rules": {
".read": true,
".write": true
}
}
I am new to react and I have already tried different ways to save this data in the realtime database of firebase, but I am successfully login the user but I am unable to save the data, I am also not getting anything in the console of Signin.jsx file, which I have created for saving the data.
Someone please help me.