0

I have a 404 page that the user gets redirected to if the URI doesn't exist for my app. The problem is that if I type in something like http://127.0.0.1:8000/sdfoijifoifs, the URL remains http://127.0.0.1:8000/gallery in the browser's search bar (even though the 404 page is displayed) instead of http://127.0.0.1:8000/sdfoijifoifs (the incorrect URL).

This is happening due to the logic happening in useEffect() but can't seem to figure out a way to rectify it. How can I fix it so that the correct URI remains when the user tries to go to a page that doesn't exist?

App. js

let { push } = useHistory();
let authToken = localStorage.getItem('token');

useEffect(() => {
  if (authToken !== null) {
    return push('/gallery');
  }

  return push('/');
}, [authToken]);

return (
  <>
    {/*https://stackoverflow.com/a/63597919*/}
    <Router>
      <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/gallery" component={Grid} />
        <Route path="/support" component={Support} />
        <Route path='/faq' component={FaqComp} />
        <Route path='/prizes' component={Prizes} />
        <Route path='/past-winners' component={PastWinners} />
        <Route path="/*" component={PageNotFound} />
      </Switch>
    </Router>
  </>
);

PageNotFound.js

return (
  <>
    <div className="pageNotFoundBody">
      <div className="containerPageNotFound">
        <h2 className="pageNotFound">404</h2>
        <h3 className="oopsPageNotFound">
          Oops, looks like the page you've navigated to cannot be found!
        </h3>
        <Link to={localStorage.getItem('token') ? "/gallery" : "/"}>
          <button className="btn mt-4">Go Home</button>
        </Link>
      </div>
    </div>
  </>
);
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
sp92
  • 873
  • 1
  • 6
  • 17
  • You might create a private route component to avoid using useEffect hook there. – Mithat Ercan Dec 24 '22 at 20:45
  • 1
    Your description doesn't quite make sense. If `push('/gallery')` is called and the app navigates to `"/gallery"` then the `Grid` component would be displayed, not `PageNotFound`. Could you create a *running* [codesandbox](https://codesandbox.io/) demo that reproduces this routing/navigation issue that we could inspect live? – Drew Reese Dec 29 '22 at 00:46

0 Answers0