Jasper Huang
Jasper Huang

Reputation: 569

React.js: State not getting update before url redirect

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?

Upvotes: 0

Views: 1144

Answers (1)

Darwin
Darwin

Reputation: 189

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

Upvotes: 2

Related Questions