简体   繁体   中英

Using Async/Await in firebase | react-redux | react-native

The code works, but I was wondering if someone could help me translate that into a better async/await syntax.

The code is fetching data using firebase api and handling the response with react-redux and thunk middleware.

I'm building an React-Native app. The "forEach" in "childSnapshot" is where I can't seem to make it neater, and I needed that to sort the score values in JSON => Node.js + Firebase orderByChild not working

  export const getScores = () => async dispatch => {
  try {
    let res =[];
    await firebase.database().ref("game_score_ref").orderByChild("score").once("value", snapshot => {
      snapshot.forEach(childSnapshot =>{
        res.push(childSnapshot.toJSON())
      })
    });
    dispatch({ type: GET_SCORES, payload: res });
  }catch(err){
    dispatch({ type: GET_SCORES_ERROR, payload: err });
  }
}

Any suggestions would be greatly appreciated!

export const getScores = () => async dispatch => {
  try {
    const score = await firebase.database().ref("game_score_ref").orderByChild("score")
    return score.once("value", snapshot => {
      const res = snapshot.map(childSnapshot => childSnapshot.toJSON())
      return dispatch({ type: GET_SCORES, payload: res });
    })
  }catch(err){
    dispatch({ type: GET_SCORES_ERROR, payload: err });
  }
}

Give this a try. I wrote something very similar for a personal project with firebase.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM