Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

react-router-dom - Redirects (Auth) example #7348

Closed
ek77git opened this issue May 16, 2020 · 3 comments
Closed

react-router-dom - Redirects (Auth) example #7348

ek77git opened this issue May 16, 2020 · 3 comments
Labels

Comments

@ek77git
Copy link

ek77git commented May 16, 2020

The below code is from "https://reacttraining.com/react-router/web/example/auth-workflow". The issue is that once you sign in it does not changes the "You are not logged in." AuthButton to the Sign out. Any idea why this is?

import React from "react";
import {
BrowserRouter as Router,
Switch,
Route,
Link,
Redirect,
useHistory,
useLocation
} from "react-router-dom";

// This example has 3 pages: a public page, a protected
// page, and a login screen. In order to see the protected
// page, you must first login. Pretty standard stuff.
//
// First, visit the public page. Then, visit the protected
// page. You're not yet logged in, so you are redirected
// to the login page. After you login, you are redirected
// back to the protected page.
//
// Notice the URL change each time. If you click the back
// button at this point, would you expect to go back to the
// login page? No! You're already logged in. Try it out,
// and you'll see you go back to the page you visited
// just before logging in, the public page.

export default function AuthExample() {
return (


    <ul>
      <li>
        <Link to="/public">Public Page</Link>
      </li>
      <li>
        <Link to="/protected">Protected Page</Link>
      </li>
    </ul>

    <Switch>
      <Route path="/public">
        <PublicPage />
      </Route>
      <Route path="/login">
        <LoginPage />
      </Route>
      <PrivateRoute path="/protected">
        <ProtectedPage />
      </PrivateRoute>
    </Switch>
  </div>
</Router>

);
}

const fakeAuth = {
isAuthenticated: false,
authenticate(cb) {
fakeAuth.isAuthenticated = true;
setTimeout(cb, 100); // fake async
},
signout(cb) {
fakeAuth.isAuthenticated = false;
setTimeout(cb, 100);
}
};

function AuthButton() {
let history = useHistory();

return fakeAuth.isAuthenticated ? (


Welcome!{" "}
<button
onClick={() => {
fakeAuth.signout(() => history.push("/"));
}}
>
Sign out


) : (

You are not logged in.


);
}

// A wrapper for that redirects to the login
// screen if you're not yet authenticated.
function PrivateRoute({ children, ...rest }) {
return (
<Route
{...rest}
render={({ location }) =>
fakeAuth.isAuthenticated ? (
children
) : (
<Redirect
to={{
pathname: "/login",
state: { from: location }
}}
/>
)
}
/>
);
}

function PublicPage() {
return

Public

;
}

function ProtectedPage() {
return

Protected

;
}

function LoginPage() {
let history = useHistory();
let location = useLocation();

let { from } = location.state || { from: { pathname: "/" } };
let login = () => {
fakeAuth.authenticate(() => {
history.replace(from);
});
};

return (


You must log in to view the page at {from.pathname}


Log in

);
}

@support
Copy link

support bot commented May 16, 2020

👋 @ek77git, we use the issue tracker exclusively for bug reports and feature requests. However, this issue appears to be a support request. For usage questions, please use Stack Overflow or Reactiflux where there are a lot more people ready to help you out.
Please feel free to clarify your issue if you think it was closed prematurely.

@support support bot closed this as completed May 16, 2020
@liuwin7
Copy link

liuwin7 commented Jul 14, 2020

In the package.json, change the version of react-router-dom to ~5.1.0.
For the latest version 5.2.0, the components which are out of the Switch won't be rendered after changing the history.
According to the commit below,

Separate history object to its own context [#7503].

@liuwin7
Copy link

liuwin7 commented Jul 15, 2020

Or, if you want to use the latest version of react-router-dom, you can use the history.listen for the AuthButton.
Referred to this.

function AuthButton() {

    let history = useHistory();
    const [, forceUpdate] = useState();

    useEffect(() => {
        return history.listen(() => {
            forceUpdate({});
        });
    }, [history]);

    return fakeAuth.isAuthenticated ? (
        <p>
            Welcome!{" "}
            <button
                onClick={() => {
                    fakeAuth.signout(() => history.push("/"));
                }}
            >
                Sign out
            </button>
        </p>
    ) : (
        <p>You are not logged in.</p>
    );
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants