Firebase, react and redux wait for store to update

情到浓时终转凉″ 提交于 2019-12-04 19:57:33

I have done what you are trying to do with a live application and used in it Firebase Auth. You need to use the Actions as a login and logout only then use componentWillMount() and componentWillReceiveProps() to check if the user is logged in:

Actions:

import { auth } from '../fire';
export const GET_USER = 'get_user';

export function getUser(){
    return dispatch => {
        auth.onAuthStateChanged(user=>{
            dispatch({
                type: GET_USER,
                payload: user
            });
        });
    };
}

export function login(email,password){
    return dispatch => auth.signInWithEmailAndPassword(email, password);
}

export function logout(){
    return dispatch => auth.signOut();
}

export function createAccount(email, password){
    return dispatch => auth.createUserWithEmailAndPassword(email, password);
}

your Reducer should have this:

import {GET_USER} from '../Actions/UserActions';

export default function( state = {loading:true}, action){
    switch (action.type){
        case GET_USER:
            return { loading: false, ...action.payload };
        default:
        return state;
    }
}

in your App.js for example, just in the start of it use this:

 componentWillMount(){
   this.props.getUser();
   if(this.props.user.loading === false && this.props.user.email === undefined){
     this.props.history.replace('/Login');
   }
 }

 componentWillReceiveProps(nextProps){
  if(nextProps.user.loading === false && nextProps.user.email === undefined){
    this.props.history.replace('/Login');
  }
 }

this is because you have your Auth credentials in your props already.

I hope this works for you..

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!