0

I am trying to fetch the data from firebase and push the data to the array one by one in a loop. But array of the fetched data doesn't show up on the React component.

I console logged and I found that as the picture below strangely shows, console.log(array.length) is 0, but console.log(array.length) show the contents of array.

enter image description here

code is as follows.

 const getThread = (threadID) => {
  return db.ref(`threads/${threadID}`).once('value')
  .then((snapshot)=>{
    return snapshot.val()
  })
}

const getThreadList = (id) => {
  let threadList = []
  return db.ref(`users/${id}/friends`).once('value')
  .then((snapshot)=>{
    let friends = snapshot.val()
    for(let key in friends){
      if(friends.hasOwnProperty(key)) {
        getThread(friends[key].threadID)
        .then((thread)=>{
          threadList.push(thread)
        })
      }
    }
    return threadList
  })
}

class SomeComponent extends Component{

  componentDidMount(){
    let { id } = this.props
    getThreadList(id)
    .then(threadList => {
      this.setState(() => ({ threadList }))
    })
  }

  render(){

    //value of threadList doses't appear

I suspect this is due to the misuse of Promise so console.log shows value but React component doesn't show anything. But I also suspect the React side and couldn't locate exactly where the problem is.

It would be much appreciated if you suggest any clue on this problem.

1 Answer 1

2

You are not waiting for the nested promises to resolve. You could use Promise.all to accomplish the task.

const getThreadList = (id) => {
  return db.ref(`users/${id}/friends`).once('value')
  .then((snapshot)=>{
    let friends = snapshot.val()
    const threads = []
    for(let key in friends){
      if(friends.hasOwnProperty(key)) {
        threads.push(getThread(friends[key].threadID))
      }
    }
    return Promise.all(threads)
  })
}

Or using Object.values

const getThreadList = id => {
  return db
    .ref(`users/${id}/friends`)
    .once("value")
    .then(snapshot => {
      const loadingThreads = Object.values(snapshot.val()).map(friend =>
        getThread(friend.threadID)
      );
      return Promise.all(loadingThreads);
    });
};
Sign up to request clarification or add additional context in comments.

2 Comments

Worked like a charm! Thank you very much.
@toshi Glad I could help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.