Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to place firebase.auth().onAuthStateChanged()

I am implementing a basic firebase authentication using react and redux. I have created protected routes as according to the react-router example found on this link and everything is working fine so far.

Now, I get the loggedIn status of the user from my auth reducer which is set on user authentication, but I want to keep the loggedIn status after page refresh using onAuthStateChanged().

Where should I place the onAuthStateChanged() function? Is there any best practice to use this?

My code for reference below:

App.js

<PrivateRoute path="/dashboard" component={Dashboard} />
<Route path="/login" component={Login} />

ProtectedRoute.js

const PrivateRoute = ({ component: Component, ...rest }) => {
const { loggedIn } = rest;
return (
    <Route {...rest} render={props => (
      loggedIn ? (<Component {...props} />) : (
        <Redirect to={{
          pathname: '/login',
          state: { from: props.location }
        }} />
      )
    )} />
  )
}

function mapStateToProps({auth}){
  return {
    loggedIn: auth.loggedIn
  }
}
export default connect(mapStateToProps)(PrivateRoute);

actions_auth.js

export const loginUser = ({ email, password }, callback ) => {
console.log(email, password)
return(dispatch) => {
  dispatch({ type: LOGIN_USER });
  auth.signInWithEmailAndPassword(email, password)
    .then(
      user => { 
        dispatch({
        type: LOGIN_USER_SUCCESS,
      payload: user
    });
    callback();
  },
  error => { 
      console.log( error.message );        
      dispatch({ 
        type: LOGIN_USER_FAIL,
        error: error.message 
      });
    }
  )
 }
}

reducer_auth.js

const INITIAL_STATE = {
  email: '',
  password: '',
  error: '',
  loading: false,
  loggedIn: false
};

export default (state = INITIAL_STATE, action) => {
  switch (action.type) {
    case EMAIL_CHANGED:
      return { ...state, email: action.payload };
    case PASSWORD_CHANGED:
      return { ...state, password: action.payload };
    case LOGIN_USER:
      return { ...state, loading: true, error: '' };
    case LOGIN_USER_SUCCESS:          
      return { ...state, ...INITIAL_STATE, user: action.payload, loggedIn: true };
    case LOGIN_USER_FAIL:
      return { ...state, error: action.error };
    case LOGOUT_USER:
      return { ...state, ...INITIAL_STATE };
    default:
      return state;
  }
};
like image 595
gianni Avatar asked Jul 27 '17 09:07

gianni


People also ask

What is onAuthStateChanged in Firebase?

According to the documentation, the onAuthStateChanged() function returns. The unsubscribe function for the observer. So you can just: var unsubscribe = firebase.

What does Firebase auth () do?

You can use Firebase Authentication to allow users to sign in to your app using one or more sign-in methods, including email address and password sign-in, and federated identity providers such as Google Sign-in and Facebook Login.

What triggers onAuthStateChanged?

onAuthStateChanged. Adds an observer for changes to the user's sign-in state. Prior to 4.0. 0, this triggered the observer when users were signed in, signed out, or when the user's ID token changed in situations such as token expiry or password change.

What does Firebase auth () CurrentUser return?

You can also get the currently signed-in user by calling CurrentUser . If a user isn't signed in, CurrentUser returns null. Note: CurrentUser might also return null because the auth object has not finished initializing.


1 Answers

You should locate it where you create redux store, should be where you render your App component. You can look here for more details. If you use firebase a lot I recommend to invest some time to set-up this great library react-redux-firebase

like image 50
ykorach Avatar answered Oct 03 '22 17:10

ykorach