4

I am trying to secure all of my routes in react for that I am trying one logic but it is not working the way I want it to be.

I am using the app.js file in that I have my routes file. I am using a functional component.

My code in app.js is:

export default function App(props) {    
  useEffect(() => {
  }, []);
  var logged = null
  var user = firebase.auth().currentUser;
  if (user) {
    logged = true
    console.log("user exist", user);    
  } else {
    logged = false
    console.log("user don't exist", logged);
  }

  const PrivateRoute = ({ component: Component, ...rest }) => (
    <Route
      {...rest}
      render={props =>
        //fakeAuth.isAuthenticated === true ? (
          logged === true ? (
          <Component {...props} />
        ) : (        
          <Redirect to="/signIn" />
        )
      }
    />
  );

   <PrivateRoute path="/features" component={FeaturePage} />

 }

This code is working fine but when I am refreshing the page or trying to go to the URL from browser it is not working.

When I am trying to add the logic in:

 var logged = null

  useEffect(() => {
    // CLEAN UP
    var user = firebase.auth().currentUser;
    if (user) {
      logged = true
      console.log("user exist", user);    
    } else {
      logged = false
      console.log("user don't exist", logged);
    }
    return () => {
      document.querySelector('.first-row').style.position = '';
    };
  }, []);

It doesn't work my question is how to create my app.js file check if the user is logged in or not every time if the user opens route from the browser or any way. It should know if it is logged in or not.

Firebase please provide some examples or any answer will be appreciated.

3 Answers 3

1

You can do it in two steps.

The first step is making logged a state with useState. It's just a local variable right now, so in your second example, change in that value is not propagated to the route. So, make it a state, add the update logic in useEffect as in your second example.

The second step is listening to user's auth state change using Firebase AuthStateListener, which listens to your auth state change (which includes the initial loading of currentUser) and calls its callback, and then updating the state based on the result.

Sign up to request clarification or add additional context in comments.

5 Comments

I used useEffect to set the value but not working that is why I used the first example which is working fine. But when you refresh that is gone and when you click on any link it works. My issue is how to set this true false mechanism even when you refresh
Did you try adding auth listeners?
What is auth listeners? Everything works fine but when refresh it doesn't hold the state. Question is where should I put this logic. So that every time anyone loads the page he or should be checked.
That's exactly what auth listener is for. Read the documentation I put above and you will understand how it works. Good luck!
Any example in React Js
1

You can achieve what you want with the help of this. Anytime when a user logout/state changes onAuthStateChanged will be called and they will be immediately redirected to login screen.

const App: React.FC = () => {
  const [authentication, setAuthState] = useState({
    authenticated: false,
    initializing: true
  });

  React.useEffect(()=>firebase.auth().onAuthStateChanged(user => {
    if (user) {
      setAuthState({
        authenticated: true,
        initializing: false
      });
    } else {
      setAuthState({
        authenticated: false,
        initializing: false
      });
    }
  }), [setAuthState]);

  if (authentication.initializing) {
    return <div>Loading</div>;
  }
  return (
    <Router>
      <div>
        <Switch>
          <Route exact path="/login" component={Login} />
          <PrivateRoute
            path="/"
            component={Home}
            authenticated={authentication.authenticated}
          />
          <PrivateRoute
            path="/join"
            component={Join}
            authenticated={authentication.authenticated}
          />
          <PrivateRoute
            path="/create"
            component={Create}
            authenticated={authentication.authenticated}
          />
        </Switch>
      </div>
    </Router>
  );
};

Comments

0

From react-firebase-js.com docs:

import * as React from "react";
import { render } from "react-dom";
import {
    FirebaseAuthProvider,
    FirebaseAuthConsumer
} from "@react-firebase/auth";
import * as firebase from "firebase/app";
import { config } from "./test-credentials";    

const App = () => {
    return (
        <div>
            <FirebaseAuthConsumer>
                {({ isSignedIn, user, providerId }) =>

                    isSignedIn === true ?

                         <Switch>
                            <Route exact path="/" component={Your Component} />
                         </Switch>
                        : <Switch>
                            <Route exact path="/signIn" component={Login} />
                        </Switch>

                } </FirebaseAuthConsumer>
        </div>
    );
};

render(<App />, document.getElementById("root"));

2 Comments

This is not a good answer can you be more specific to my question.
@NilaySingh I've updated my code to be more specific to your question

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.