Source:  Twitter logo

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;
  }
};

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

7 users liked answer #0dislike answer #07
ykorach profile pic
ykorach

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).