Z
Z
zhodino2018-08-03 19:44:43
JavaScript
zhodino, 2018-08-03 19:44:43

How to rewrite user request from firebase to es6 syntax?

This code is working fine

export const fetchUser = () => {
  return (dispatch) => {
    firebase.auth().onAuthStateChanged(function(user) {
      if (user) {
        var user = firebase.auth().currentUser;
        if (user) {
            console.log(user);
          } else {
            console.log('error');
        }
      } else {
        console.log('error');
      }
    });
  };
}

But if I rewrite it like this, then User becomes null
export const fetchUser = () => {
  return async (dispatch) => {
    try {
      let user = await firebase.auth().onAuthStateChanged((user) => { return user });
      if(user){
        let User = await firebase.auth().currentUser;
        console.log(User);
      }
    }catch(e){
      console.log(e);
    }

  };
}

Please tell me where is the mistake

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Eugene, 2018-08-06
Hz @joniks

Wrote you here of course tin. You need to learn the materiel - async / await syntax is used with promises, but you are trying to shove it in an incomprehensible place and are waiting for some kind of magic.
let user = await firebase.auth().onAuthStateChanged((user) => { return user });
look, if firebase.auth().onAuthStateChanged returns a promise, then you can write like this
let user = await firebase.auth().onAuthStateChanged();
here
let User = await firebase.auth().currentUser;
await is not needed at all.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question