2

I want to create authentication system.I made a form on submitting i send user credentials and receive a token in return using ajax response. Now I want to redirect to home page after token is received.

I am using react router 4,redux-thunk middleware I tried to do this with context but it did not worked.

onSubmit(e){

  e.preventDefault();

  this.setState({isLoading:true});

  this.props.login(this.state).then(function(response){

    console.log('token', response.data.token);

    //Redirect to home component

  });

}
Shawn Mehan
  • 4,274
  • 9
  • 28
  • 48
Ankit sharma
  • 39
  • 2
  • 5

2 Answers2

1

For that you could use the Redirect component: https://reacttraining.com/react-router/web/api/Redirect

You could have a state variable that indicate if the user is logged, and set it to true in the then method after user is logged. In the render method use that state to control the rendering of the Redirect component.

Johnny Zabala
  • 1,848
  • 1
  • 9
  • 14
1

Just expanding on what Johnny said above. This is a great example from the react-router docs:

class Login extends React.Component {
  state = {
    redirectToReferrer: false
  }

  login = () => {
    fakeAuth.authenticate(() => {
    this.setState({ redirectToReferrer: true })
   })
  }

render() {
  const { from } = this.props.location.state || { from: { pathname: '/' } }
  const { redirectToReferrer } = this.state

  if (redirectToReferrer) {
    return (
      <Redirect to={from}/>
    )
  }

 return (
  <div>
    <p>You must log in to view the page at {from.pathname}</p>
    <button onClick={this.login}>Log in</button>
  </div>
  )
 }
}

So you would:

//Redirect to home component

setState({loggedIn:true)}

and in your render function:

if (this.state.loggedIn) {
  return (<Redirect to='/home')
}
phillercode
  • 149
  • 9