Home > Back-end >  React not responding to observable when logging in
React not responding to observable when logging in

Time:03-24

I am using Mobx to manage the user login status for my react webapp and firebase for authorization.

I can't seem to figure out why my webapp does not respond to the user actually logging in. It always is stuck on the default value of logged out.

Here is my code:

const App: React.FC<Props> = ({ basename }) => {

  var isSignedIn = true
  


  onAuthStateChanged(auth, (user) => {
    if (user) {
      // User is signed in, see docs for a list of available properties
      // https://firebase.google.com/docs/reference/js/firebase.User
      console.log("IS SIGNED IN");
      isSignedIn = false;

    } else {
      // User is signed out
      isSignedIn = true;
      console.log("IS NOT SIGNED IN");
    }
  });

  return (
    <BrowserRouter basename={basename}>
      <ThemeProvider>
        <Switch>
          <Route path="/error" component={ErrorsPage} />
          <Route path="/logout" component={Logout} />
          {
            !isSignedIn?
              <Route>
                <PublicRoutes />
              </Route>
                :
              <>
                <MasterLayout>
                  <PrivateRoutes />
                </MasterLayout>
              </>
          }
        </Switch>
      </ThemeProvider>
    </BrowserRouter>
  );
};

export { App };

When I run it, it correctly sends me to the login page and in the console I see that it writes "NOT SIGNED IN". After I sign in, I see that in the console it updates to "SIGNED IN" but nothing happens on the page? I can't access the regular website and it keeps redirecting me to the signin page, indicating that it does not recognize me as a signed in user.

However, if I set the default value of isSignedIn to true, it correctly directs me to the main page.

What am I doing wrong here?

CodePudding user response:

Instead of assigning directly like

isSignedIn = true;

In react you should use the useState hook. Declare the variable (and it's setter function)

const [isSignedIn, setIsSignedIn] = useState(false);

Then later to update the value

setIsSignedIn(true);

Otherwise, the value is reset whenever the component re-renders. https://reactjs.org/docs/hooks-state.html

  • Related