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
222 views
in Technique[技术] by (71.8m points)

reactjs - Javascript - console data shows length of 2 but contains only one value

I have the following firestore code, which simply appends some object into an array, which is then passed to a react component for populating a list.

 export const getUsers =async (tarinerId) => {
      let data = [];
      try{
      let ref = await db
        .collection("users")
        .orderBy("createdAt")
        .limit(3)
        .get();
    
          if (ref.empty) {
           return new Promise.reject("No User Found")
          }
          ref.forEach(doc => {
     data.push({
              name: doc.data().first_name+" "+doc.data().last_name,
              id: doc.data().id,
              email: doc.data().email,
              createdAt: doc.data().createdAt
            })
}
    console.log(data)
    return Promise.resolve({userData: data})
    } catch(error) {console.log(error}
}       
    

And the userData is passed into a react component. Once upon receiving i want to pop out one last element from the array.

<Component userData={userData.data} />

And inside the Component I am poping out the data.

But the issue is console.log from the function is printing out a length of 4 items, but there are only 3 items inside it.

My first guess is about call by reference, but how come the component pop affects the console.log on the function which gets executed already? Or is there something obvious that I am missing here?

question from:https://stackoverflow.com/questions/66067396/javascript-console-data-shows-length-of-2-but-contains-only-one-value

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

1 Reply

0 votes
by (71.8m points)

Your ref might have an empty record. That might be what returning an extra empty object


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

...