0

I have a currentUser object in App.state that starts out as an empty object before the user is logged in and gets set with the user's information once the user successfully logs in.

Upon a successful login, I call setState({currentUser: user}) which prompts an update. Then, in componentDidUpdate(), I check whether a change to currentUser prompted the update, and if it did, I call window.location.href = "/home", and render a <Home /> component.

  componentDidUpdate(prevProps, prevState) {
    // if the user just successfully logged in, redirect to home
    if (
      Object.keys(prevState.currentUser).length === 0 && // was an empty object
      Object.keys(this.state.currentUser).length > 0 // now it's been set
    ) {
      window.location.href = "/home"; // render the Home component, passing this.state.currentUser as a prop
    }
  }

in render():

  <Route
    path="/home"
    render={(props) => (
      <Home currentUser={this.state.currentUser} />
    )}
  />

The problem is, when the user gets redirected to /home, this.props.currentUser is still an empty object in the Home.props. So even though an update to this.state.currentUser (where it explicitly isn't an empty object anymore) is what triggered the change to the /home Route, this.state.currentUser is still an empty object when I pass it down as a prop.

What am I misunderstanding here?

4
  • 2
    Afaik you're not supposed to change location.href directly; doing that will completely discard your app state and start over (because the browser moves to another location). Commented Jul 10, 2020 at 7:59
  • 1
    You can programmatically navigate using this.props.history.push('/home') Commented Jul 10, 2020 at 8:01
  • 1
    Does this answer your question? Programmatically navigate using react router Commented Jul 10, 2020 at 8:01
  • 1
    you might want to use this.props.history.push() if you are using react-router Commented Jul 10, 2020 at 8:03

1 Answer 1

2

window.location.href is a valid way to change the route. However, this actually causes a reload or a refresh of the entire page. It is similar to how you manually type this url in the browser. Therefore, all the states are removed or cleared.

As suggested in this link, you are supposed to use the following:

this.props.history.push('/home')

And in order to pass parameters, you may check this link

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Just started learning how to use Routers, this was very helpful.

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.