I made a form , here I am trying to get all datails of form to the profile page
Here's form code:
`
<script type="module">
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.10/firebase-app.js";
import { getDatabase, set, ref, get, child } from "https://www.gstatic.com/firebasejs/9.6.10/firebase-database.js";
const firebaseConfig = {
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const db = getDatabase();
const SelectRole = document.getElementById('selectRole');
const facebook = document.getElementById('furl');
const twitter = document.getElementById('turl');
const insta = document.getElementById('instaurl');
const linkdin = document.getElementById('lurl');
const submit = document.getElementById('sub_btn');
const username = document.getElementById('uname');
function InsertData() {
set(ref(db, "TheUsers/" + username.value), {
Username: username.value,
// Password : password.value,
Role: SelectRole.value,
FacebookURL: facebook.value,
TwitterURL: twitter.value,
InstagramURL: insta.value,
LinkedinURL: linkdin.value,
})
.then(() => {
alert("Data stored successfully");
window.location = "profile.html";
})
.catch((error) => {
alert("unsuccessful,error" + error);
});
}
//------------------------------------------------------ASSIGN EVENT TO BTN------------------------------------//
submit.addEventListener('click', InsertData);
</script>
\`
After filling the form page... page redirect to the profile page and should have shows all datails ......but heres at profile page all fields shows undefine.
Here's profile page code:
`
<script type="module">
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.10/firebase-app.js";
import { getDatabase, set, ref, get, child } from "https://www.gstatic.com/firebasejs/9.6.10/firebase-database.js";
const firebaseConfig = {
....
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const db = getDatabase();
const SelectRole = document.getElementById('selectRole');
const facebook = document.getElementById('furl');
const twitter = document.getElementById('turl');
const insta = document.getElementById('instaurl');
const linkdin = document.getElementById('lurl');
const submit = document.getElementById('sub_btn');
const username = document.getElementById('uname');
function selectdata() {
const dbref = ref(db);
get(child(dbref, "TheUsers/" + username.value)).then((snapshot) => {
if (snapshot.exists()) {
username.value = snapshot.val().Username;
SelectRole.value = snapshot.val().Role;
facebook.value = snapshot.val().FacebookURL;
twitter.value = snapshot.val().TwitterURL;
insta.value = snapshot.val().InstagramURL;
linkdin.value = snapshot.val().LinkedinURL;
}
else {
alert("No data Found")
}
})
.catch((error) => {
alert("error" + error);
})
}
// submit.addEventListener('click',selectdata);
window.onload = selectdata;
</script>
`
Thanks for any help.
Related
I am currently trying to make an account page for users using data from Firebase auth, database, and storage. The only problem with the code is that the text and images that need data from the database(username and profile picture) are appearing as undefined so it seems like the database isn't returning data
the code:
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.13.0/firebase-app.js"
import { getAuth, createUserWithEmailAndPassword, signInWithEmailAndPassword, signOut, onAuthStateChanged } from 'https://www.gstatic.com/firebasejs/9.13.0/firebase-auth.js';
import { getDatabase, set, ref } from 'https://www.gstatic.com/firebasejs/9.13.0/firebase-database.js';
import { getStorage, ref as storageRef, getDownloadURL } from 'https://www.gstatic.com/firebasejs/9.13.0/firebase-storage.js'
const firebaseConfig = {
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: ""
};
//Initiate firebase services
const app = initializeApp(firebaseConfig);
const auth = getAuth(app)
const database = getDatabase(app)
const storage = getStorage(app)
//Get image folder from storage
const imageFolder = storageRef(storage, "gs://betterbadgeworld.appspot.com/profile-pictures")
//Get user UID and accountData
let user = onAuthStateChanged(auth, (user)=>{
if (user) {
var user = auth.currentUser
return user
}
else {
return
}
})
let accountData = onAuthStateChanged(auth, (user)=>{
if (user) {
var userUID = user.uid
var accountData = ref(database, 'users/' + user.uid)
console.log(accountData)
return accountData
}
else {
return
}
})
//Add username and profile picture to website with accountData
function initializeData(accountData) {
//Get profile picture file name
let userProfilePicture = accountData.profilePicture + ".png"
//Set username in text box
const usernameText = document.createTextNode(accountData.username)
const usernameBox = document.getElementById('username')
usernameBox.appendChild(usernameText)
//Get profile picture div, make gs:// link, and get downloadURL for it
const profilePicBox = document.getElementById("profile-picture")
var profileGSLink = imageFolder + "/" + userProfilePicture
var profileLink = getDownloadURL(storageRef(storage, profileGSLink))
//Make image element and use profileLink as source
let img = document.createElement("img");
img.src = profileLink;
profilePicBox.appendChild(img);
}
initializeData(accountData)
the code that isn't returning the data:
let accountData = onAuthStateChanged(auth, (user)=>{
if (user) {
var accountData = ref(database, 'users/' + user.uid)
console.log(accountData)
return accountData
}
else {
return
}
})
I was running my next.js app and trying to fetch user I am getting "cannot read properties of undefined" error
And following error in the console
Below is the code I was using
import Ewitter from './Ewitter.json';
import ethers from 'ethers';
import { useState, useEffect } from 'react';
const ContractABI = Ewitter.abi;
const ContractAddress = '0x5FbDB2315678afecb367f032d93F642f64180aa3';
const Ethereum = typeof window !== 'undefined' && (window as any).ethereum;
const getEwitterContract = () => {
const provider = new ethers.providers.Web3Provider(Ethereum);
const signer = provider.getSigner();
const EwitterContract = new ethers.Contract(
ContractAddress,
ContractABI,
signer
);
return EwitterContract;
};
const useEwitter = () => {
// const Ewitter = getEwitterContract();
const [currentAccount, setCurrentAccount] = useState<string>('');
const [currentUser, setCurrentUser] = useState<string>('');
const connect = async () => {
try {
if (!Ethereum) {
alert('Please install MetaMask');
return;
}
const accounts = await Ethereum.request({
method: 'eth_requestAccounts',
});
if (accounts.length === 0) {
alert('Please unlock MetaMask');
return;
}
const account = accounts[0];
console.log('connected to account: ', account);
setCurrentAccount(account);
} catch (errors) {
console.log(errors);
}
};
useEffect(() => {
if(!Ethereum){
console.log("No ethereum wallet found, please install metamask")
return ;
}
connect();
}, []);
useEffect(() =>{
if(currentAccount){
getUser();
}
}, [currentAccount])
const getUser = async ()=>{
const contract = getEwitterContract();
const user = await contract.getUser(currentAccount);
const {avatar, bio, name, username, wallet} = user;
console.log(user);
return user;
}
return { connect, account: currentAccount };
};
export default useEwitter;
#Update1
I've changed import ethers from 'ethers' to import {ethers} from 'ethers' and now I'm facing this error
If unable to understand properly or if you want to see the whole codebase then this is the link to the github repo
https://github.com/ChiragDogra/ewitter/blob/userIssue/dapp/hooks/useEwitter.ts
believe or not I just had that issue.
the problem is how you are importing ethers. Should be
import { ethers } from "ethers";
How can I add a user to the users collection logging in with Gmail?
I tried the addUser but it does not work. I'm quite new to Firebase v9
//firebase
import { signInWithPopup, GoogleAuthProvider } from "firebase/auth";
import { auth, signInWithGoogle, db } from "../../Firebase/utils";
import { doc, setDoc, collection } from "firebase/firestore";
const Login = (props) => {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const addUser = async () => {
const userRef = doc(db, "users", auth.currentUser);
setDoc(userRef);
};
useEffect(() => {
addUser();
}, []);
const googleHandler = async () => {
signInWithGoogle.setCustomParameters({ prompt: "select_account" });
signInWithPopup(auth, signInWithGoogle)
.then((result) => {
// This gives you a Google Access Token. You can use it to access the Google API.
const credential = GoogleAuthProvider.credentialFromResult(result);
const token = credential.accessToken;
// The signed-in user info.
const user = result.user;
// redux action? --> dispatch({ type: SET_USER, user });
addUser();
console.log(auth.currentUser, "login page");
})
.catch((error) => {
// Handle Errors here.
const errorCode = error.code;
const errorMessage = error.message;
// The email of the user's account used.
const email = error.email;
// The AuthCredential type that was used.
const credential = GoogleAuthProvider.credentialFromError(error);
// ...
});
};
return (
<>
<form>
<Button onClick={googleHandler}>Login with Gmail</Button>
</form>
</>
);
};
export default Login;
These are my package.json just to be sure:
This is what the console.log(auth.currentUser) shows:
UPDATE:
const addUser = async (userId) => {
const userRef = doc(db, "users", userId);
return await setDoc(userRef, { ...data });
};
useEffect(() => {
addUser();
}, []);
const googleHandler = async () => {
signInWithGoogle.setCustomParameters({ prompt: "select_account" });
signInWithPopup(auth, signInWithGoogle)
.then(async (result) => {
// This gives you a Google Access Token. You can use it to access the Google API.
const credential = GoogleAuthProvider.credentialFromResult(result);
const token = credential.accessToken;
// The signed-in user info.
const user = result.user;
// redux action? --> dispatch({ type: SET_USER, user });
// addUser();
const { isNewUser } = getAdditionalUserInfo(result);
if (isNewUser) {
await addUser(user.uid);
} else {
console.log("User already exists");
}
})
.catch((error) => {
// Handle Errors here.
const errorCode = error.code;
const errorMessage = error.message;
// The email of the user's account used.
const email = error.email;
// The AuthCredential type that was used.
const credential = GoogleAuthProvider.credentialFromError(error);
// ...
});
};
The doc() function takes Firestore instance as first argument and the rest are path segments (strings) so you cannot pass currentUser object there. Also there might be a chance that auth.currentUser. You can use isNewUser property to check if the user has just signed up or is logging in again and then add the document. Try refactoring the code as shown below:
signInWithPopup(auth, signInWithGoogle)
.then(async (result) => {
const user = result.user;
const { isNewUser } = getAdditionalUserInfo(result)
if (isNewUser) {
await addUser(user.uid);
} else {
console.log("User already exists")
}
})
const addUser = async (userId) => {
const userRef = doc(db, "users", userId);
return await setDoc(userRef, {...data});
};
I'm using firebase twitter authentication for my project. The auth variable returning the credentials does not contain the account's twitter username but everything else.
I need to work with the username, is there a way to work around this?
Users shown in the console look like thisFirebase Console
How do I get the respective identifier of a uid?
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.1.2/firebase-app.js";
import { getAuth, signInWithPopup, TwitterAuthProvider } from "https://www.gstatic.com/firebasejs/9.1.2/firebase-auth.js";
const app = initializeApp(firebaseConfig);
const provider = new TwitterAuthProvider();
const auth = getAuth();
document.querySelector('button').addEventListener('click', authenticate);
function authenticate() {
signInWithPopup(auth, provider)
.then((result) => {
const credential = TwitterAuthProvider.credentialFromResult(result);
const token = credential.accessToken;
const secret = credential.secret;
const user = result.user;
console.log(result)
}).catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
const email = error.email;
const credential = TwitterAuthProvider.credentialFromError(error);
console.log(error);
});
}
Is there a way to get the username from this 'auth' variable, check below code for ref
import { getAuth } from "https://www.gstatic.com/firebasejs/9.1.2/firebase-auth.js"
const auth = getAuth();
auth.onAuthStateChanged(user => {
if(user){
// window.location.href = "/home/index.html"
}else{
}
})
I think you mean Twitter handle (also called screen name) by "username"
const provider = new TwitterAuthProvider();
const userInfo = await signInWithPopup(auth, provider);
console.log(userInfo._tokenResponse.screenName) // twitter handle
Hello there you can try this:
firebase.auth().signInWithPopup(new firebase.auth.TwitterAuthProvider())
.then((userCredential) => {
// here you get the username
console.log(userCredential.additionalUserInfo.username);
})
.catch((error) => {
console.log("error occurred");
});
or else you can get the info using this if you are having id :
let url = `https://api.twitter.com/1.1/users/show.json?user_id=${the_uid_from_provider_data}`;
fetch(url)
.then(response => {
let data = response.json();
console.log(data);
})
.catch(error => {
// handle the error
});
For me it works like that
const res = await signInWithPopup(auth, provider);
const user = res.user;
const username = user.reloadUserInfo.screenName;
console.log(`username #${username}`);
I have the following setup to connect to firebase but for some reason in the browser console it shows that auth.createUserWithEmailAndPassword() is not a function. Is there something wrong with my code?
import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.0.2/firebase-app.js';
import { getAuth, createUserWithEmailAndPassword } from 'https://www.gstatic.com/firebasejs/9.0.2/firebase-auth.js';
import { getFirestore } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-firestore.js"
// TODO: Replace the following with your app's Firebase project configuration
const firebaseConfig = {
" my config here "
};
const app = initializeApp(firebaseConfig);
const auth = getAuth();
const db = getFirestore();
var button = document.getElementById("button").addEventListener("click", function () {
var email = document.getElementById("email").value;
var phone = document.getElementById("phone").value;
var password = document.getElementById("password").value;
auth.createUserWithEmailAndPassword(email, password).then(cred => {
console.log(cred);
})
});
edit: I removed auth. from auth.createUserWithEmailAndPassword(email, password).then(cred => { console.log(cred); and now it is giving me the current error: ```Uncaught (in promise) TypeError: Cannot create property
'_canInitEmulator' on string 'heheboi#gmail.com'
at _performFetchWithErrorHandling (firebase-auth.js:1983)
at _performApiRequest (firebase-auth.js:1958)
at _performSignInRequest (firebase-auth.js:2030)
at signUp (firebase-auth.js:5330)
at createUserWithEmailAndPassword (firebase-auth.js:5978)
at HTMLButtonElement.<anonymous> (register.html:48) ``
Just update your code to the latest Firebase SDK 9:
import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.0.2/firebase-app.js';
import { getAuth, createUserWithEmailAndPassword } from 'https://www.gstatic.com/firebasejs/9.0.2/firebase-auth.js';
import { getFirestore } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-firestore.js"
// TODO: Replace the following with your app's Firebase project configuration
const firebaseConfig = {
" my config here "
};
const app = initializeApp(firebaseConfig);
const auth = getAuth();
const db = getFirestore();
var button = document.getElementById("button").addEventListener("click", function () {
var email = document.getElementById("email").value;
var phone = document.getElementById("phone").value;
var password = document.getElementById("password").value;
createUserWithEmailAndPassword(auth, email, password).then(cred => {
console.log(cred);
}).catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
// ..
});
});
You are already importing createUserWithEmailAndPassword. You can't use auth.createUserWithEmailAndPassword anymore. You can find here the latest docs.