props.history.push() not working in metronic theme

748 views Asked by At

After login I am not redirecting to my users page I am using react metronic theme. I think something is wrong with props.history.push() Here what I have done so far.

Main component is below:

ReactDOM.render(
  <MetronicI18nProvider>
    <MetronicLayoutProvider>
      <MetronicSubheaderProvider>
        <MetronicSplashScreenProvider>
          <ToastContainer/>
          <App store={store} persistor={persistor} />
        </MetronicSplashScreenProvider>
      </MetronicSubheaderProvider>
    </MetronicLayoutProvider>
  </MetronicI18nProvider>,
  document.getElementById("root")
);

App component:

export default function App({ store, persistor }) {
  return (
    /* Provide Redux store */
    <Provider store={store}>
      {/* Asynchronously persist redux stores and show `SplashScreen` while it's loading. */}
      <PersistGate persistor={persistor} loading={<LayoutSplashScreen />}>
        {/* Add high level `Suspense` in case if was not handled inside the React tree. */}
        <React.Suspense fallback={<LayoutSplashScreen />}>
          {/* Override `basename` (e.g: `homepage` in `package.json`) */}
          <BrowserRouter>
            {/*This library only returns the location that has been active before the recent location change in the current window lifetime.*/}
            <MaterialThemeProvider>
              {/* Provide `react-intl` context synchronized with Redux state.  */}
              <I18nProvider>
                {/* Render routes with provided `Layout`. */}
                <Routes />
              </I18nProvider>
            </MaterialThemeProvider>
          </BrowserRouter>
        </React.Suspense>
      </PersistGate>
    </Provider>
  );
}

This is my routers component

   <Switch>
            {getToken()==null? (
                <Route>
                    <AuthPage/>
                </Route>
            ) : (
                <Redirect from="/auth" to="/"/>
            )}

            <Route path="/error" component={ErrorsPage}/>

            {getToken()==null ? (
                <Redirect to="/auth/login"/>
            ) : (
                <Layout>
                    <BasePage/>
                </Layout>
            )}
        </Switch>

this is my base component

export default function BasePage() {
    return (
        <Suspense fallback={<LayoutSplashScreen/>}>
            <Switch>
                <Redirect exact from="/" to="/allUsers"/>
                <ContentRoute path="/allUsers" component={AllUsers}/>
                <Redirect to="error/error-v1"/>
            </Switch>
        </Suspense>
    );
}

this is action which I fire after sign In button

 props.onLogin(values).then((res) => {
            toast.success('Login Successfull')
            props.history.push('/allUsers')
        }).catch((err) => {
            console.log('error', err)
            toast.error('Login failed')
        })

and I have same AuthPage component.

api is fired success fully, token is saved successfully and toaster is shown 'Login successful'. But I am not redirecting to my desired page. But if I refresh then I am redirected to home page.

Can anyone help me with this

** history.push is working in /allUsers route. But not working in Login component

Update: I think I found what I am doing wrong. I don't need to perform any history.push() action when I will save token(which is I am doing in my onLogin action) it should automatic redirect to AllUsers Page. I changed my approach to as below and now it is working.

  const {isAuthorized} = useSelector(
        ({mainAuth}) => ({
            isAuthorized: mainAuth.user != null,
        }),
        shallowEqual
    );

replaced getToken with isAuthorized

But history.push() not working here is still mystery.

4

There are 4 answers

3
Maheshvirus On

I think in your case you are not getting history reference in props. You can try these two solutions. withRouter from react-router & useHistory from react-router-dom.

import { withRouter } from 'react-router'; 
componentName(){
   const { match, location, history } = this.props
    history.push('Your Page')
}
export default withRouter(componentName);

OR

import { useHistory } from "react-router-dom";

component(){
    const history = useHistory();
    history.push('Your Page')
}
1
Shyam On

Please use history package version as v4.9.0 for react-router v5.2.0

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

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

0
fxdxpz On

I guess I have been able to reproduce your issue here but not sure yet about solution. But my while guess is that your root most Switch doesn't get triggered when you do history.push, so those expressions with getToken are not evaluated and thats why we are not redirected anywhere.

If I have time later to play around more, I might update this answer.

0
DevLoverUmar On

Try this

import { useHistory } from "react-router-dom";

export someclass/ReactComponent{
.
.
.
const history = useHistory();

 props.onLogin(values).then((res) => {
            toast.success('Login Successfull')
            history.push('/allUsers')
        }).catch((err) => {
            console.log('error', err)
            toast.error('Login failed')
        })
}
}

Or refer to this thread