Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect with "componentDidMount()" : problem (React)

I have some code that works. It immediately reroutes a user from the /test page to the FinishedPaying page. It is as so:

class Test extends Component {
  renderRedirect = () => {
      return <Redirect to="/FinishedPaying" />;
  };
  componentDidMount() {
    this.renderRedirect();
  }
...

The following code is meant to send a Paypal transaction, then route the user to the /FinishedPaying page. All of the other logic is working as expected:

export default class Pay extends React.Component {
  state = {
    userInput: ""
  };
  renderRedirect = () => {
      return (
        <Redirect
          to="/FinishedPaying"
          userInput={this.state.userInput}
        />
      );
  };
  componentDidMount() {
    this.setState({ userInput: this.props.userInput });
    this.renderRedirect();
  }

  render() {
    const onSuccess = payment => {
      axios
        .post(
          "http://amazonaws.com:3000/ethhash",
          {
            userInput: this.props.userInput,
          }
        )

        .then(response => console.log(response.data, payment))

        .catch(function(error) {
          console.log(error);
        });
    };

    return (
      <div>
        <PaypalExpressBtn
          onSuccess={onSuccess}
        />
      </div>
    );
  }
}

Not sure why the second code block is working. It is my understanding that this.renderRedirect() should fire after all of the other logic has happened. It does not seem to be firing at all. Any feedback is appreciated :)

like image 615
Hanley Soilsmith Avatar asked Dec 05 '25 23:12

Hanley Soilsmith


1 Answers

you can put it in your render like:

render() {
    if (this.state.redirect){
        return <Redirect
            to="/FinishedPaying"
            userInput={this.state.userInput}
            />;
    }
    const onSuccess = payment => {...}

As soon as you change your redirect value in state for true you will be redirected.

like image 76
Sergey Pugach Avatar answered Dec 08 '25 20:12

Sergey Pugach