I have created an react project, here is the code:-
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 = async () => {
const provider = new GoogleAuthProvider();
try {
const result = await signInWithPopup(auth, provider);
return result;
} catch (error) {
console.error('Error during sign-in:', error);
}
};
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;
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;
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:-
Attempting to save user ID: RdMQaBouH2RY5rVozaw5b9dSAro1
Signin.jsx:23 Error during sign-in or saving user ID: TypeError: databaseRef.child is not a function
at Object.handleGoogleSignIn [as onClick] (Signin.jsx:18:1)
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 got to the position from where the process of saving the data has been initialized but it is not saving the data, there is some problem while creating the dataref.child().
Someone please help me.