firebase auth delayed on refresh

后端 未结 4 1558
醉话见心
醉话见心 2021-02-05 20:50

Hard refreshes on my SPA React/Firebase application does not maintain auth state on immediate execution of a function. I have a workaround, but it\'s sketchy.

My react

4条回答
  •  走了就别回头了
    2021-02-05 21:56

    Works by managing localStorage. Here is example how I do it.

      constructor(props) {
        super(props);
    
        let authUser = null;
    
        // setting auth from localstorage
        for (let key in localStorage) {
          if (key === storageId) {
            authUser = {};
            break;
          }
        }
    
        this.state = {authUser};
      }
    
      componentDidMount() {
        firebase
          .auth
          .onAuthStateChanged(authUser => {
    
            if (authUser) {
              localStorage.setItem(storageId, authUser.uid);
            } else {
              localStorage.removeItem(storageId);
            }
    
            // change state depending on listener
            authUser
              ? this.setState({authUser})
              : this.setState({authUser: null});
          });
      }
    

提交回复
热议问题