Revircs
Revircs

Reputation: 1352

React v4 and Redux: Update URL after API call to show new route?

In my React application, I am trying to direct the user to "/" after a successful login. If possible, I need the page to not refresh after a successful login. Here is the code I have for when the API needs to be called (resp.data is sent when the user is authenticated):

handleFormSubmit = event => {
    event.preventDefault();
    API.signin({
      username: this.state.username,
      password: this.state.password
    }).then(resp => {
      if (resp.data) {

      // console.log(resp);
      // window.location.replace(resp.data);
      window.history.pushState({}, null, resp.data);

    } else {
      console.log("Authentication was unsuccessful, or passport did not send back information.")
    }
    }).catch(function (error) {
      console.log(error);
    });
  }

Using window.history.pushState({}, null, resp.data); works for changing the URL. However, the components don't update (I have BrowserRouter routes specified for /login, /signup, and /). Additionally, window.location.replace(resp.data); refreshes the page. Is there a way to do this through react?

Upvotes: 0

Views: 37

Answers (1)

Kyle Richardson
Kyle Richardson

Reputation: 5645

You can use the withRouter HoC provided by the react-router package to inject some properties into your components. You're interested in the history object from react-router, not the history object on window.

import {withRouter} from 'react-router'

class MyComponent extends React.PureComponent {
  handleFormSubmit = event => {
    ...
    API.signin({
      ...
    }).then(resp => {
      if(resp.data) {
        const {history} = this.props
        history.push('/', {
          data
        })
      }
    })
  }
}

export default withRouter(MyComponent)

Using withRouter will make {match, location, history} objects available in your component. With the above pattern your user will be redirected to your '/' route provided you have a <Route path='/'/> component in your <Router/> tree. The data will be available on location.state.data. (You'll need to wrap your home component with withRouter as well to have access to the location object.

Upvotes: 1

Related Questions