0

I am trying to redirect after signup or login to the homepage ('/').

I have tried putting in iterations of this.props.redirect('/') in the handleLogin function.

Also tried to create another function setting Redirect to true to trigger a react-router redirect.

Looking to either pass two functions thru onClick or add a next step to existing functions.

constructor() {
    super()

    this.state = {
      email: '',
      password: '',
      isLoggedIn: false
    }

    this.handleInput = this.handleInput.bind(this)
    this.handleLogIn = this.handleLogIn.bind(this)\
  }

  componentDidMount () {
    if (localStorage.token) {
      this.setState({
        isLoggedIn: true
      })
    } else {
      this.setState({
        isLoggedIn: false
      })
    }
  }

  handleInput (e) {
    this.setState({
      [e.target.name]: e.target.value
    })
  }

  handleLogIn (e) {
    e.preventDefault()
    axios.post('http://localhost:3001/users/login', {
      email: this.state.email,
      password: this.state.password
    })
    .then(response => {
      localStorage.lettuceId = response.data.id
      console.log(localStorage.lettuceId)
      localStorage.token = response.data.token
      this.setState({isLoggedIn: true})
    })
    .catch(err => console.log(err))
  }

class LogIn extends Component {

    render() {
        return (
            <div className="main-form">
                <h2>Log In</h2>
                <form className="form-wrapper">
                <div>
                    <input type='text' name='email' className="form" placeholder='Email' onChange={this.props.handleInput} />
                </div>
                <div>
                    <input type='password' name='password' className="form" placeholder='Password' onChange={this.props.handleInput} />
                </div>
                <input value='Submit' type='submit' className="button" onClick={this.props.handleLogIn} />
                </form>
            </div>
        );
    }
}
everyday_potato
  • 103
  • 1
  • 1
  • 9
  • which version of react-router do you use and where do you attempt to redirect – Shubham Khatri Feb 21 '19 at 17:31
  • 1
    Could be a possible duplicate of [Programmatically Navigate using react-router](https://stackoverflow.com/questions/44127739/programmatically-navigate-using-react-router/44128108#44128108) – Shubham Khatri Feb 21 '19 at 17:33

1 Answers1

0

If you are wrapping you component with withRouter then you can use history object in props to redirect like

//After some actions
this.props.history.push('/')

Or as your are setting state after login you can use like

 handleRedirect = () => {
 this.state.isLoggedIn ? <Redirect to='/' /> : null
 }

And call this method in render function(You need to import redirect from router if you want to use the later option)

Sumanth Madishetty
  • 2,054
  • 1
  • 7
  • 16