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!

2
  • Have you created a router? somewhere? Commented Oct 20, 2020 at 4:46
  • Yes, this is just a small snippet of my code (the actual code is largely irrelevant to my problem and I did not want to post that much) Commented Oct 20, 2020 at 5:16

2 Answers 2

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')} />
)
Sign up to request clarification or add additional context in comments.

1 Comment

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!
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>

4 Comments

Yeah I had tried that, but it did not work and Eslint threw errors... I am starting to wonder if I am using the router correctly as all the research I could find tell me to use history.push or the Redirect component. Thanks for responding!
@AkshatAdsule have you tried passing Login Component in <Route path="/login" component={Login}/>
Would I just pass in component={<Login onSubmit={...}/>}?
No That would not work you need to pass your Component in that or you can use render option of route

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.