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?

Jasper Huang
  • 501
  • 2
  • 7
  • 15
  • 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). –  Jul 10 '20 at 07:59
  • 1
    You can programmatically navigate using `this.props.history.push('/home')` – Meet Zaveri Jul 10 '20 at 08:01
  • 1
    Does this answer your question? [Programmatically navigate using react router](https://stackoverflow.com/questions/31079081/programmatically-navigate-using-react-router) –  Jul 10 '20 at 08:01
  • 1
    you might want to use `this.props.history.push()` if you are using react-router – Maximilian Haindl Jul 10 '20 at 08:03

1 Answers1

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

Darwin
  • 189
  • 2
  • 9