0

I am building a login system -- when the user fills in the form - I've created a redux action to "authenticate" the user -- so when this.props.authData.isLogged is true -- I want to invoke the navigate function to bounce the user to the home page. However, this.props.router is undefined? But I've defined the withRouter?

import React, { Component } from 'react'
//import { render } from 'react-dom'
//import { withRouter } from 'react-router-dom'
import { withRouter } from 'react-router';

// components
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { fetchAuthentication } from '../../actions/authAction';

import LoginSyncValidationForm from './LoginSyncValidationForm'


// this is a class because it needs state
class Login extends Component {

  constructor(props, context) {
    super(props, context);
    this.submit = this.submit.bind(this);
  }

  componentDidMount() {    
    // console.log('this', this)
  }

  submit (data) {
    this.props.fetchAuthentication(data);
  }

  navigate() {
    console.log("navigate", this)
    //this.props.router.push('/home');
  }

  render() {
    console.log(this.props.authData)

    if(this.props.authData.isLogged){
      this.navigate();
    }

    return (
      <div className="Page">
        <h2>Login</h2>
        <LoginSyncValidationForm onSubmit={this.submit} />
      </div>
    )
  }
}


function mapStateToProps(state) {
  return {
    authData: state.auth
  };
}

function mapDispatchToProps(dispatch) {
 return bindActionCreators({ fetchAuthentication }, dispatch);
}


const {object} = React.PropTypes
Login.propTypes = {
  router: object
}
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Login))
The Old County
  • 109
  • 7
  • 40
  • 99

2 Answers2

1

Could you please try this out. In React router V4 the API has been changed a lot and browserHistory.push() can not be used as before. Now you get access to history object in your props inside the component. Calling the push method on history object will push a new entry onto the history stack.

  navigate() {
    this.props.history.push('/home');
  }
Ravindra Ranwala
  • 18,704
  • 6
  • 38
  • 55
0

You can make use of Redirect component like so:

import { Redirect } from 'react-router'

...
navigate() {
    return <Redirect to="/home" />
}
Amr Aly
  • 3,620
  • 2
  • 13
  • 30