Firebase database doesn't return data - javascript

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
}
})

Related

doc is not a function error on deleting document in firebase

TypeError: doc is not a function
i am using the firebase documentation delete document code
deleteDoc(doc(db,"cafe",id))
bt here it is showing paused due to exception in browser
// Import the functions you need from the SDKs you need
import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.14.0/firebase-app.js';
import { getFirestore,doc, collection, getDocs,addDoc,deleteDoc } from 'https://www.gstatic.com/firebasejs/9.14.0/firebase-firestore.js'
const firebaseConfig = {
apiKey: "AIzaSyC_qbiPqjPCoK4yQ2lzjeinQhx7Co1mEbE",
authDomain: "cafe-review-804eb.firebaseapp.com",
databaseURL: "https://cafe-review-804eb-default-rtdb.asia-southeast1.firebasedatabase.app",
projectId: "cafe-review-804eb",
storageBucket: "cafe-review-804eb.appspot.com",
messagingSenderId: "933248008537",
appId: "1:933248008537:web:a15fe6338d071f2a3c0c48",
measurementId: "G-2JX7DVQTM2"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const db = getFirestore(app)
const cafeList = document.querySelector("#cafe-list")
const form = document.querySelector("#add-cafe-form")
function renderCafe(doc){
let li = document.createElement('li')
let name = document.createElement('span')
let city = document.createElement('span')
let cross = document.createElement('div')
li.setAttribute('data-id',doc.id)
name.textContent = doc.data().name
city.textContent = doc.data().city
cross.textContent = 'x'
li.appendChild(name)
li.appendChild(city)
li.appendChild(cross)
cafeList.appendChild(li)
//delete data
cross.addEventListener('click', (e) => {
e.stopPropagation()
let id = e.target.parentElement.getAttribute('data-id')
console.log(id)
deleteDoc(doc(db,"cafe",id))
})
}
const querySnapshot = await getDocs(collection(db, "cafe"));
querySnapshot.forEach((doc) => {
renderCafe(doc)
});
// save form
form.addEventListener('submit', (e)=> {
e.preventDefault()
const docRef = addDoc(collection(db,"cafe"),{
name: form.name.value,
city: form.city.value
})
form.name.value = ""
form.city.value = ""
})
The problem is that you have two definitions of doc inside your renderCafe function:
The doc you imported from the Firestore SDK with import { ... doc, ... } from.
The doc parameter you pass to renderCafe in function renderCafe(doc){.
Since the parameter is closer in scope than the import, inside your renderCafe function doc refers to the parameter and not the function you imported.
To solve this problem, give the parameter a different name like ``:
function renderCafe(dbdoc){
let li = document.createElement('li')
let name = document.createElement('span')
let city = document.createElement('span')
let cross = document.createElement('div')
li.setAttribute('data-id',dbdoc.id)
name.textContent = dbdoc.data().name
city.textContent = dbdoc.data().city
cross.textContent = 'x'
li.appendChild(name)
li.appendChild(city)
li.appendChild(cross)
cafeList.appendChild(li)
//delete data
cross.addEventListener('click', (e) => {
e.stopPropagation()
let id = e.target.parentElement.getAttribute('data-id')
console.log(id)
deleteDoc(doc(db,"cafe",id))
})
}

How to use Firebase to upload images in Next.js?

I'm following a video tutorial about Nextjs and have seen that the version of Firebase he is using is out of date. I managed to follow all the steps reading the documentation until I got to this point.
Searched here and found some interesting answers on how to achieve the option to upload images to Firebase. Here the link
Have tried all solutions and none of them have worked. I get an error message:
FirebaseError: Firebase Storage: An unknown error occurred, please check the error payload for server response. (storage/unknown)
Bad Request
Here the code I'm trying:
import Image from "next/image";
import { useSession } from "next-auth/react";
import { FaceSmileIcon } from "#heroicons/react/24/outline";
import { VideoCameraIcon, PhotoIcon } from "#heroicons/react/20/solid";
import { useRef } from "react";
import { db, storage } from "../firebase";
import { collection, addDoc, serverTimestamp, doc, setDoc } from "firebase/firestore";
import { useState } from "react";
import {ref, uploadString, getDownloadURL, getStorage} from "firebase/storage";
function InputBox() {
const {data: session} = useSession();
const inputRef = useRef(null);
const filePickerRef = useRef(null);
const [imageToPost, setImageToPost] = useState(null);
const sendPost = async (e) => {
e.preventDefault();
if(!inputRef.current.value) return;
const colRef = collection(db, "posts")
await addDoc(colRef, {
message: inputRef.current.value,
name: session.user.name,
email: session.user.email,
image: session.user.image,
timestamp: serverTimestamp(),
}).then((document) => {
if(imageToPost) {
const storageRef = ref(storage, `posts/${document.id}`);
uploadString(storageRef, imageToPost, "data_url").then((snapshot) => {
getDownloadURL(snapshot.ref).then(URL => {
setDoc(doc(db, "posts", document.id),
{imageToPost: URL}, {merge: true}
);
});
})
removeImage();
}
})
inputRef.current.value = "";
};
const addImageToPost = (e) => {
const reader = new FileReader();
if(e.target.files[0]) {
reader.readAsDataURL(e.target.files[0]);
}
reader.onload = (readerEvent) => {
setImageToPost(readerEvent.target.result);
}
};
const removeImage = () => {
setImageToPost(null);
};
return ( <HERE THE REST OF THE CODE>
Don't be mad at me. I really tried to do my best to find a solution and to not post here.
Any help will be really appreciated because I can't figure out what is wrong, because as mentioned before I tried all options I found so far.
BTW also tried to assign storage to getStorage() before const storageRef = ref(storage, `posts/${document.id}`);
Like so:
.then((document) => {
if(imageToPost) {
const storage = getStorage();
const storageRef = ref(storage, `posts/${document.id}`);
<MORE CODE>
And my firebase.jsfile:
import { initializeApp } from 'firebase/app';
import { getStorage } from "firebase/storage";
const firebaseConfig = {
apiKey: "APIKEY-HERE",
authDomain: "AUTHDOMAIN-HERE",
projectId: "PROJECT-ID-HERE",
storageBucket: "STORAGE-BUCKET-HERE",
messagingSenderId: "MESSAGING-SENDER-HERE",
appId: "APPID-HERE"
};
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
const storage = getStorage(app);
export { db, storage };
Try this, this worked for me: Firebase: "^9.0.0"
addDoc(dbInstance, {
message: inputRef.current.value,
name: session?.user?.name,
email: session?.user?.email,
image: session?.user?.image,
timestamp: serverTimestamp(),
}).then((doc) => {
if (imageToPost) {
const storageRef = ref(storage, `posts/${doc.id}`);
uploadString(storageRef, imageToPost, "data_url").then((snapshot) => {
getDownloadURL(snapshot.ref).then((url) => {
addDoc(dbInstance, { postImage: url });
});
});
removeImage();
}
});
inputRef.current.value = "";
Try this. I have used firebase v8.6.3.
const docRef = firebase.firestore().collection("colection_name").doc();
const storageRef = firebase.storage().ref();
const uploadTask = storageRef.child('/posts/' + imageToPost.name).put(imageToPost);
console.log(uploadTask)
uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED, // or 'state_changed'
(snapshot) => {
// Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
console.log('Upload is ' + progress + '% done');
switch (snapshot.state) {
case firebase.storage.TaskState.PAUSED: // or 'paused'
console.log('Upload is paused');
break;
case firebase.storage.TaskState.RUNNING: // or 'running'
console.log('Upload is running');
break;
}
},
(error) => {
// A full list of error codes is available at
// https://firebase.google.com/docs/storage/web/handle-errors
switch (error.code) {
case 'storage/unauthorized':
// User doesn't have permission to access the object
break;
case 'storage/canceled':
// User canceled the upload
break;
// ...
case 'storage/unknown':
// Unknown error occurred, inspect error.serverResponse
break;
}
},
() => {
// Upload completed successfully, now we can get the download URL
uploadTask.snapshot.ref.getDownloadURL().then((downloadURL) => {
console.log('File available at', downloadURL);
docRef.set({
message: inputRef.current.value,
name: session.user.name,
email: session.user.email,
image: downloadURL,
});
});
}
);
If you don't want the upload progress and error then you can get rid of that codes and directly proceed to getDownloadURL.

getting undefined data on page load

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.

Is there a way to give unique id numbers to a page?

I get the data of all the movies on my home page. But I don't want to do this on the Admin.html page. On the admin page, when I click on the name of the movie, I want to go to the page related to that movie. For example, when I click on the movie "Schindler's List" which movieId is 3 (Admin.html?movieId=3), I want to go to a page with only Schindler's List movie information. It will show only Schindler List's img,score,name. How can I achieve this?
Admin.html
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.4.0/firebase-app.js";
import { getDatabase, set, ref, update, get, child } from "https://www.gstatic.com/firebasejs/9.4.0/firebase-database.js";
import { getAuth, createUserWithEmailAndPassword, signInWithEmailAndPassword, onAuthStateChanged, signOut } from "https://www.gstatic.com/firebasejs/9.4.0/firebase-auth.js";
const firebaseConfig = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: ""
};
const app = initializeApp(firebaseConfig);
const db = getDatabase(app);
const auth = getAuth(app);
btnCreate.addEventListener('click',(e)=>{
var movieId = document.getElementById('movieId').value;
var movieName = document.getElementById('movieName').value;
var movieScore = document.getElementById('movieScore').value;
var movieImage = document.getElementById('movieImage').value;
set(ref(db, 'Movies/' + movieId), {
movieId: movieId,
movieName: movieName,
movieScore: movieScore,
movieImage : movieImage
});
});
let html = '';
var body = document.getElementById('editor');
var body2 = document.getElementById('week');
function AddItemsToTable(name,score,img,id){
let html='';
const movies=`
<div class="content"><img src="${img}"><p>${name}</p> <p> <img src="img/mutlu.png" class="emoji"><a class="scoretxt">${score}</a> </p> </div>
`;
html = movies;
body.innerHTML += html;
body2.innerHTML+=html;
}
function AddAllItemsToTable(TheMovies){
body.innerHTML="";
TheMovies.forEach(element => {
AddItemsToTable(element.movieName, element.movieScore, element.movieImage,element.movieId);
});
}
function getAllDataOnce(){
const dbRef=ref(db);
get(child(dbRef,"Movies"))
.then((snapshot)=>{
var movies=[];
snapshot.forEach(childSnapshot => {
movies.push(childSnapshot.val())
});
AddAllItemsToTable(movies);
});
}
window.onload= getAllDataOnce;

auth.createUserWithEmailAndPassword is not a function

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.

Categories

Resources