Pedro Vieira
Pedro Vieira

Reputation: 2316

How Redirect when a Promise is Resolved?

I'm trying do implement a onClick() function that when the user click the Submit button, it saves the information and take the user to another page. I tried a few ways with no success.

import { Redirect } from 'react-router-dom'

<Button onClick={() => 
  saveUserData(this.props.selectedElement) // the promise is resolving
    .then(<Redirect to='/other_url' />)
  }>
  Submit
</Button>

I also tried:

.then(() = > {<Redirect to='/other_url' />})

Upvotes: 0

Views: 1714

Answers (1)

Roy.B
Roy.B

Reputation: 2106

from https://reacttraining.com/react-router/web/api/Redirect you need to render <Redirect /> to navigate to a new location

I would have done something like this:

state = {
    redirect: false
  }

  handleClick = () => {
    saveUserData(this.props.selectedElement)
      .then(() => this.setState({ redirect: true }));
  }

  render () {
    const { redirect } = this.state;

     if (redirect) {
       return <Redirect to='/other_url' />;
     }

     return (
  ...

       <Button onClick={this.handleClick}>
           Submit
       </Button>

  ...
 )
}

Upvotes: 1

Related Questions