Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
163 views
in Technique[技术] by (71.8m points)

reactjs - How to access the data within object fetch from firestore

How can i get access to the data from the object that i fetch from firebase forestore. I have code in which i get complete object from firebase like

localInvoice:{
  name:Ali, 
  date:29/09/2020,
  Phone:033562100555
 }

but when it comes to access inner values of objects then i get error message. The error message is like, for example if i want to access the name

const[invoice, setInvoice]=useState({
  name:Ali, 
  date:29/09/2020,
  Phone:033562100555
 });
console.log(invoice.name);
//error message --> Cannot read property 'name' of undefined

This is my Code in which

  1. First I simply add data to my firestore
  2. Secondly i am fetching the same data i added before. I am passing name, phone, date, string date as props to get the same data i added from firestore

if my question in not conveying properly then please ask me it will be helpfull if changes should be done in code given in links

question from:https://stackoverflow.com/questions/66060439/how-to-access-the-data-within-object-fetch-from-firestore

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is because your currentInvoice is an array, since you store it this way:

setCurrentInvoice(
   snapshot.docs.map((doc) => ({ id: doc.id, data: doc.data() }))
)

You can access the name like this:

console.log(currentInvoice[0].data.name);

However, if you only want to store the first invoice, you can do it so:

 setCurrentInvoice(snapshot.docs[0].data());

And then access the name like you wanted first:

console.log(invoice.name);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...