Firebase Storage - Retrieve all Folders [duplicate] - firebase

This question already has answers here:
How to get a list of all files in Cloud Storage in a Firebase app?
(20 answers)
Closed 6 months ago.
Im new to Firebase storage and i can't for the life of me figure out how to retrieve/list all the folders in my storage.
I have tried reading the docs and i can't find anything on how to solve my specific issue.
Any help here is greatly appreciated. Thank you!

You can close this topic as resolved.
Solved by doing this.
const testRef = ref(storage, '/');
useEffect(() => {
listAll(testRef)
.then((res) => {
res.prefixes.forEach((folderRef) => {
// All the prefixes under listRef.
// You may call listAll() recursively on them.
console.log(folderRef.name) //this is where i got the folder names.
});
res.items.forEach((itemRef) => {
// All the items under listRef.
});
}).catch((error) => {
// Uh-oh, an error occurred!
});
}, []);

Related

How to create a user in FireBase without signing in? [duplicate]

This question already has answers here:
How to just create an user in Firebase 3 and do not authenticate it?
(2 answers)
Firebase kicks out current user
(19 answers)
Closed 24 days ago.
I have a function to create users in a FireBase web application called registerWithEmailAndPassword.
Here is the code:
const registerWithEmailAndPassword = async (name, email, password) => {
try {
const res = await auth.createUserWithEmailAndPassword(email, password);
const user = res.user;
... do some useful things with the user ...
} catch (err) {
console.error(err);
alert(err.message);
}
};
The function above does pretty much what I need, but one big drawback due to the way auth.createUserWithEmailAndPassword works is that I get automatically signed in with the newly created user.
This is what I do not need and do not want.
How can I properly avoid this signing in "side effect" ?

Can I use 'react-native-firebase' and 'firebase' at the same time in ReactNative project? [duplicate]

This question already has answers here:
What's the difference between Firebase JavaScript SDK and react-native-firebase
(3 answers)
What are the differences between react-native-firebase & Firebase npm packages
(1 answer)
Which library has a better performance react-native-firebase or firebase? [closed]
(1 answer)
Closed 2 years ago.
Now I am using Firebase authentication in React Native project.
I started with 'firebase' module at the beginning of the project. And after that I added 'react-native-firebase' module for some reason.(crashlytics, Deep link etc)
Then in one *.js file(e.g: Login.js), can I use those two modules at the same time?
Login method of those two module is different a little each other.
e.g: firebase
import firebaseAuth from '../config';
... ...
firebaseAuth.signInWithEmailAndPassword(this.state.email, this.state.password)
.then(() => this.props.navigation.navigate('CreateRoom'))
.catch(error => this.setState({ errorMessage: error.message }), alert(this.state.errorMessage));
#react-native-firebase/auth
import auth from '#react-native-firebase/auth';
... ...
try {
const doLogin = await auth().signInWithEmailAndPassword(
this.state.email,
this.state.password,
);
if (doLogin.user) {
this.props.navigation.navigate('Main');
} else {
alert('User info incorrect.')
}
} catch (err) {
console.log('Login Error', err);
}
Is it possible to use those 2 modules at the same time?
And what is the difference of those 2 modules?
Any answer will be appreciate. Thank you.

Uncaught TypeError: db.collection is not a function for a real-time database in firebase [duplicate]

This question already has answers here:
Firebase cannot retrieve data from database "db.collection is not a function"
(3 answers)
Closed 3 years ago.
when I try to access my collection I get the following error. My firebase app is initialized inside my main app component.
I didn't include the config object here but I know that it works because I'm also using firebase auth in my app which works perfectly fine.
App.js
componentDidMount(){
if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig);
}
}
Component where I am trying to make a db call
componentDidMount(){
const db = firebase.database();
const ref = db.collection('Users/Notes').doc()
let getDoc = ref.get()
.then(doc => {
if (!doc.exists) {
console.log('No such document!');
} else {
console.log('Document data:', doc.data());
}
})
.catch(err => {
console.log('Error getting document', err);
});
}
I am rendering this component immediately by including it in App.js, I don't know if that might somehow be a problem?
You're mixing up Firebase database products.
firebase.database() gives you an object to deal with data in Firebase Realtime Database. But the code you're writing to work with that object looks like it's using the Firestore API, which is a completely different database product.
If you want an object that lets you make queries against Firestore collections, you should use firebase.firestore(), and you will need to import the library that gives you access to that API.
To be sure that you're using the correct database, please review the documentation for getting started with both Firebase Realtime Database and Firestore.
Change
const db = firebase.database();
into this:
const db = firebase.firestore();
More info Here

Cloud Firestore returning undefined in events

Everyone.
I'm trying to make a script that creates data in Cloud Firestore and returns it. But I can't access the data (undefined), why?
That's my script:
const tools = require('./bin/firebase');
const app = require('express')();
// eslint-disable-next-line new-cap
const server = require('http').Server(app);
const io = require('socket.io')(server);
server.listen(3000);
const db = tools.connectFirebase();
io.on('connection', (socket) => {
const ipAddress = socket.handshake;
console.log(ipAddress.address);
db.collection('socket').doc('refresh').collection('2').doc('1').set({
name: 'Los Angeles',
});
db.collection('socket').doc('refresh').onSnapshot((doc) => {
console.log('Current data: ', doc.data());
});
socket.on('disconnect', () => {
console.log('Disconnected.');
});
});
And that's what this script returns:
Image
And finally, that's the Cloud Firestore data that I wanted to return: Image
I need to return those nodes, so: Basically, I need something like this:
{
1: {
name: "Los angeles:",
},
2: {
name: "Washington DC",
},
}
Basically, I need to fix it, anyone can help me to deal with it?
(Sorry about my English skills, I'm trying to improve it)
Try this below. Your set method is returning before the data is written. It's returning a future(promise). You have to wait on it either with .then() or await to be able to read the data back.
db.collection('socket').doc('refresh').collection('2').doc('1').set({
name: 'Los Angeles',
}).then(() => db.collection('socket').doc('refresh').onSnapshot((doc) => {
console.log('Current data: ', doc.data());
}));
Edit: oh sorry, you are reading /socket/refresh, which is probably empty. The subcollections under it are not sent as a json as you described above. You have to do db.collection('socket').doc('refresh').collection('2').doc('1') to read them. You cannot get a subtree as a json like you expected.
Go ahead and put some data into /socket/refresh and hopefully it's not going to be undefined anymore.

Integrating FireStore/Stripe/iOS/Cloud Functions

I am a newbie to all the technologies mentioned. So, I apologize in advance if this question shouldn't be here.
So I am trying to write the firestore equivalent of the example stripe-firebase realtime database-cloud functions integration provided by firebase. It is located here: https://github.com/firebase/functions-samples/blob/master/stripe/functions/index.js
I successfully converted the exports.createStripeCustomer function. But I am having trouble with addPaymentSource.
This is what I have so far:
exports.addPaymentSource = functions.firestore.document('Users/{userId}/paymentSources/{paymentID}').onWrite((change, context) => {
let newPaymentSource = change.after.data();
let token = newPaymentSource.token;
return functions.firestore.document(`Users/${context.params.userId}`).get('customer_data')
.then((snapshot) => {
return snapshot.val();
}).then((customer) => {
return stripe.customers.createSource(customer, {newPaymentSource});
}).then((response) => {
return change.after.ref.parent.set(response);
}, (error) => {
return change.after.ref.parent.child('error').set(userFacingMessage(error));
}).then(() => {
return reportError(error, {user: context.params.userId});
});
});
Deployment happens successfully, but the function fails with the following error.
TypeError: functions.firestore.document(...).get is not a function
at exports.addPaymentSource.functions.firestore.document.onWrite (/user_code/index.js:73:77)
at Object. (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:112:27)
at next (native)
at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:28:71
at __awaiter (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:24:12)
at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:82:36)
at /var/tmp/worker/worker.js:728:24
at process._tickDomainCallback (internal/process/next_tick.js:135:7)
Clearly 'get' doesn't seem to be a function. I got this function from the following reference document. https://firebase.google.com/docs/reference/functions/functions.firestore.DocumentSnapshot
I seem to be missing something. I have been stuck on this for a couple of days. So, any help would be greatly appreciated. Thanks in advance.
use firebase-admin
const admin = require('firebase-admin');
exports.addPaymentSource = functions.firestore.document('Users/{userId}/paymentSources/{paymentID}').onWrite((change, context) => {
let newPaymentSource = change.after.data();
let token = newPaymentSource.token;
return admin.firestore().doc(`Users/${context.params.userId}`).get('customer_data')
// what you have to do
});
});
The functions package is used for triggering functions. You can use the following methods:
onCreate
onUpdate
onDelete
onWrite
(more here: https://firebase.google.com/docs/firestore/extend-with-functions)
To use the get() method, you'll want to use the firebase-admin package - you can then access firestore from admin.firestore()
(firebase-admin: https://www.npmjs.com/package/firebase-admin)

Resources