0

so I have a bug that I can't seem to solve. Currently I am using react with react router, however I cannot seem to get react to redirect to a page. Here is a expert from my code (keep in mind this is a functional component)

<Route path="/login">
  <Login
    onSubmit={(user) => {
      login(user, (status) => {
        if (status == 200) {
          history.push('/home');
        } else {
          history.push('/login');
        }
      });
    }}
  />
</Route>

(For reference, I have a login component which takes in a onSubmit callback and in which I call a predefined login method in check the status of the response from my backend and redirect accordingly)

When I run this code and redirect, I get a error that says

Unhandled Rejection (TypeError): Cannot read property 'push' of undefined

And just to be clear, I have defined history in the first few lines of my component

let history = useHistory();

Any help will be greatly appreciated!

Akshat Adsule
  • 63
  • 1
  • 10

2 Answers2

1

You can use Redirect from react-router-dom

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

...

<Route path="/login">
  <Login
    onSubmit={(user) => {
      login(user, (status) => {
        if (status == 200) {
           return <Redirect to="/home" />
        } else {
          return <Redirect to="/login" />
        }
      });
    }}
  />
</Route>
Ferin Patel
  • 3,424
  • 2
  • 17
  • 49
1

history is resolving to undefined so you are trying to invoke undefined.push('path'), hence the error. You need to make history accessible within the scope of the component like this:

import {useHistory} from 'react-router-dom'

const App = () => (
const history = useHistory()
return <Login onSubmit={() => history.push('/path')} />
)
Alex Mckay
  • 3,463
  • 16
  • 27
  • This worked for me! I created a useHistory instance in my login component, and passed that to my callback. Thanks so much for your answer! – Akshat Adsule Oct 20 '20 at 05:14