Vlady Veselinov
Vlady Veselinov

Reputation: 5401

Redirecting to 404 component without changing URL in the browser?

I'm making a universal redux app where the user is redirected to a 404 route if he asks for a non-existing url, but I have this problem where if you click the back button it doesn't let you go back.

Is there a way to redirect to a 404 route without changing the url?

Here's how my routes look like:

export default (
    <Route path="/" component={App}>
        <IndexRoute component={MainPage} />
        <Route path="venues/:venueName" component={VenueContainer} />
        <Route path="404" component={NotFound} />
        <Route path="*" component={NotFound} />
    </Route>
);

Calling this redux action to redirect:

import { push } from 'react-router-redux';

export default function redirect404() {
    return (dispatch) => {
        dispatch(push('/404'));
    };
}

What I have right now works but I can see some user-experience frustration coming out of it.

EDIT: I think the issue is arising from the routes with params, such as: <Route path="venues/:venueName" component={VenueContainer} />. React-router sees a match and doesn't redirect to: <Route path="*" component={NotFound} />.

I'm requesting data from an external API and if there is none I want to show the 404 without changing the URL:

import axios from 'axios';
import redirect404 from './utilActions';

export function fetchVenue() {
    return (dispatch) => {
        dispatch({
            type: 'FETCH_VENUE',
            payload: axios.get('http://externalAPI.com'),
        })
        .catch((error) => {
            console.info(error);
            dispatch(redirect404());
        });
    };
}

Upvotes: 3

Views: 2339

Answers (2)

Robiseb
Robiseb

Reputation: 1606

Try using replace instead of push

  • push - Pushes a new location to history, becoming the current location
  • replace - Replaces the current location in history.

react-router-redux

import { push } from 'react-router-redux';

export default function redirect404() {
  return (dispatch) => {
    dispatch(replace('/404'));
  };
}

Upvotes: 2

Mario Tacke
Mario Tacke

Reputation: 5488

Remove the /404 route entirely and don't redirect. Right now you user is redirected to /404 every time you cannot match the route. Your * path works fine as a catch all.

Upvotes: 0

Related Questions