Search code examples
reactjsbrowser-history

history.push() giving 404


I am trying to use redirect user on authentication using history but for some reason, it is giving me 404. These are my routers and with them, I am exporting history.

export let history = createBrowserHistory();

<Router history={history}>
        <div>
            <Header />
        </div>
        <Switch>
            <Route path="/" component={LoginPage} />
            <Route path="/dashboard" component={ExpenseDashboardPage} />
            <Route path="/add" component={AddExpense} />
            <Route path="/edit/:id" component={EditExpensePage} />
            <Route path="/help" component={HelpPage} />
            <Route component={NotFoundPage} />
        </Switch>
    </Router>

in my app.js I am importing it and using it. In my console, I have logout so it should redirect to '/' but is not.

let hasRendered = false;
const renderApp = () => {
    if (!hasRendered) {
        ReactDOM.render(jsx, document.getElementById("root"));
        hasRendered = true;
    }
}

firebase.auth().onAuthStateChanged((user) => {
    if (user) {
        console.log("Log in");
        store.dispatch(startSetExpense()).then(() => {
            renderApp();
            if (history.location.pathname === '/') {
                history.push('/dashboard');
            }
        });
    }
    else {
        console.log('Logout');
        renderApp();
        history.push('/');
    }
});

Edit 1: I tried to debug the program and found that the problem is not with routes but Router or history. The routes are working perfectly fine with BrowserRouter.

Edit 2: renderApp just render the app

let hasRendered = false;
const renderApp = () => {
    if (!hasRendered) {
        ReactDOM.render(jsx, document.getElementById("root"));
        hasRendered = true;
    }
};

Solution

  • Use react-router v5.2.0 and history v4.9.0 to make this work.

    https://codesandbox.io/s/quizzical-dan-z3725

    OR

    Try using BrowserHistory https://reactrouter.com/web/example/basic

    seems there is some issue with customHistory when we use different version

    Originally answered here: https://stackoverflow.com/a/64623542/1723410