Get data from firebase/react js - reactjs

How to get username field from "users" collection in document?
I just want to display in settings user usernamesettings
firestore
I tried to get data from firestore, but it's not working

I'm not sure what your problem is exactly but you can try looking at the docs:
https://firebase.google.com/docs/firestore/query-data/get-data
If you will provide more detail then I might be able to give you direct code for the problem.
import { doc, getDoc } from "firebase/firestore";
const docRef = doc(db, "cities", "SF");
const docSnap = await getDoc(docRef);
if (docSnap.exists()) {
console.log("Document data:", docSnap.data());
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
Above code allows you to get the data of a specific document.
the docSnap.data() function returns an object which contains all the fields of a document. You can use it like this for example:
docSnap.data()['name']
Another issue could be with rules. Rules can be used to setup specific conditions and allow access allow to your database when those certain conditions are followed. You could have setup rules but then later never really followed the rules in your app. I would like you to check your rules and then check the app to see if your code follows them.
Hope this helps :D

Related

Save value to Firestore on Stripe successful payment status

I want to write the user free-input form data to Firestore based on them successfully completing the Stripe checkout through the PaymentElement. I was first trying to do so based on the stripe.confirmPayment method response, which did not work well. Any ideas or practical examples on how can this be implemented? I have also tried using Stripe Webhooks, but I am unsure how to pass the user free-input form data there. Can this generally be handled from the front end, or should I create Firebase function?
const { error } = await stripe.confirmPayment({
elements,
confirmParams: {
return_url: window.location.href
}
});

How to Update this mobile no field to firestore database when all the data have route to this screen

How do i update this mobile no field to firestore database i am unable to find the doc id. i tried many times but it showing me error that doc id is missing which doc id should i have to put please make a help for me in this case. Thankyou.
const ItemDetails = ({ route }) => {
const[values, setValue] = useState('')
let data = route.params
console.log(data)
const updateValue = () => {
db.collection("FinalData")
.doc()
.update({
mobile_no: values
})
.then(function () {
alert("Mobile Number Updated Successfully")
})
}
Okay, you do not know which doc id to put.
In Firestore, you can only update an existing document.
Right now, what you want to do with this line db.collection("FinalData").doc().update(...) is to update a document, but you have not told firestore which document to remove the old mobile no from and put the new mobile no in.
Another way to understand this is we can assume that your firestore database is a book. What you want to do with this line db.collection("FinalData").doc().update(...) is to tell firestore to please change mobile no to 'bla bla bla' on page (you didn't give any page number). So you see, firestore can not change anything because it does not which page to change.
So the doc id being referred to is the id of the document you want to correct.
This mobile no, is probably one of your users mobile number, so get the document (which could be something like user-settings, user-details or so) id.
Then you put that document id as shown below:
db.collection("FinalData").doc('PUT-DOC-ID-HERE').update(...)

Let users create elements that only they can see in Firebase (in React)

I recently started learning firebase and i find it great. I was able to let users register/login with email and password and once they are on the app they can create "Cards" with some data. However any user that creates an account on my app can then view and delete, edit, etc. any Card created by any user.
My question is simply how can i only display Cards strictly to the users who created them only?
Here is my code up to now:
useEffect(() => {
const cardRef = firebase.database().ref('Cards')
cardRef.on('value', (snapshot) => {
const cards = snapshot.val()
const cardslist = []
for (let id in cards) {
cardslist.push({id, ...cards[id] })
}
setCardslist(cardslist)
})
},[])
//in my jsx i then have cardslist which displays the cards
<div>{cardslist}</div>
Here is what you need to do:
1 - Make sure every "card" document has a "creator" field, so you can filter the query with something like...
your_query().where("creator", "==", current_viewer_id)
2 - Make sure you use Firestore Rules, to limit read/write operations on a card to only the creator of the card. Your use case is one of the first examples you'll see in Firestore Rules documentation and explainer videos.
Good luck! You're almost there.

Why doesn't Collection#find work for offline members who have no roles? (discord.js)

My Goal
My goal is to figure out why Collection#find returns undefined when I try to find a user in my server, but they're offline and have no roles.
Expectation
Usually the console logs an array of all the properties of the user
Actual Result
The console logs Collection#find, as undefined if the user in my server is offline and has no roles
What I've Tried
I've tried using Collection#get, but it turns out that it returns the same response. I've tried searching this up on Google, but no one has asked this question before.
Reproduction Steps
const Discord = require('discord.js');
const client = new Discord.Client();
const {prefix, token} = require('./config.json');
client.once('ready', () => {
console.log('Client is online');
const user = client.users.cache.find(user => user.tag === 'Someone#1234');
console.log(user);
};
client.login(token);
Make sure that whoever is helping you, whether it's an alt account or your friend, that they have no roles, and they're completely offline in your server
Output:
Client is online undefined
I had the same problem. I don't know why this happens, but I used this line to fix that:
((await m.guild.members.fetch()).filter(mb => mb.id === "The ID")).first()`
Basically, this collect all the members, then filters them with the property you want, and the first() at the end is to make it a single object instead of a collection.
Instead of the user.tag property, try using the user.username and the user.discriminator properties. This worked for me
const user = client.users.cache.find(user => user.username === 'Someone' && user.discriminator === '1234');
Also check spelling, capitalization, ect.
A simple solution to my problem is just create an async function and use await guild.members.fetch() to cache the users and then use Collection#find to get the user.

Delay in Firestore to create a new document in the users collection

I hope someone can help me with this issue.
I'm currently working on a project in which I use firebase to create new users. So, when someone sign a new user up, firebase creates a new user, then it sends a promise to firestore, so it can create a new document in a collection called 'users', so I can access some user data, as name, last name and initials.
My problem is that, when I sign a new user up, the account is instantly created in firebase, but it takes a long time to create a new document with the user data in firestore. When I say a long time, I mean 10, 20 minutes or even more. Thus, an account is created with undefined data, until firestore decide to create new document.
The described procedure is shown in the code below:
export const signUp = newUser => {
return (dispatch, getState, { getFirebase }) => {
const firebase = getFirebase()
const firestore = getFirebase().firestore()
firebase.auth().createUserWithEmailAndPassword(
newUser.email,
newUser.password
).then(resp => {
return firestore.collection('users').doc(resp.user.uid).set({
firstName: newUser.firstName,
lastName: newUser.lastName,
initials: newUser.firstName[0] + newUser.lastName[0]
}).then(() => {
dispatch({ type: 'SIGN_UP_SUCCESS' })
})
}).catch(err => {
dispatch({ type: 'SIGN_UP_FAIL', err })
})
}
}
I'm using redux-firestore and react-redux-firebase as dependencies to connect my project to firebase. But it does not seem to be the problem, because firestore works seamlessly for other functionalities of the project, as add and delete new data to the user when its document is finally created, or when I try to delete an user, it also works fine.
So, I would be glad if someone could find an explanation for this delay and help me to overcome this problem.
I believe you're following The Net Ninja's series (I am too). If you follow what he did exactly (here) it will work. I've personally diffed yours and my implementation with his, and the only thing that was different was the semicolons. Try adding semicolons after each line. Perhaps the chaining of promises confuses the compiler?
It still won't work when you signup, then signout repeatedly. You need to refresh after each signout.
After some time I realized that the problem was not the code or firebase. The problem was something in the structure of the project it self.
In order to solve this problem, I needed to get rid of
"#testing-library/jest-dom"
"#testing-library/react"
"#testing-library/user-event"
In package.json. Then install the dependencies again.

Resources