4

I'm trying to redirect the user after a submit button has been pressed in my react app, but redirect never happens. After submit button I'm sending data via axios to an API, then I want to redirect. This is done by having first set the state for redirect to false in my constructor, after having sent the axios call I'm trying to set it's state to true then conditionally render a react router redirect if the value is true.

I have confirmed that Axios actually sends data to the back end. But no idea why the conditional render does not run after the value is set to true. Any ideas? :)

My code:

import React from 'react';
import Button from '@material-ui/core/Button';
import CssBaseline from '@material-ui/core/CssBaseline';
import axios from 'axios';
import { Redirect } from 'react-router';

class confirmWithdraw extends React.Component {
  constructor() {
    super();
    this.state = {
      redirect: false
    };

    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleEvent = e => {
    this.setState({ [e.target.name]: e.target.value });
  };

  handleSubmit = e => {
    e.preventDefault();
    const amount = sessionStorage.getItem('amount');
    const serverCardNumber = sessionStorage.getItem('cardnumber');
    axios({
      method: 'post',
      url: '/api/whidrawal',
      data: {
        amount,
        serverCardNumber
      }
    }).then(() => this.setState({ redirect: true }));
  };

  render() {
    const { redirect } = this.state;
    if (redirect) {
      return <Redirect to="/moneyform" />;
    }
    return (
      <React.Fragment>
        {redirect ? <Redirect to="/moneyform" /> : null}
        <div>
          Select action -> Withdraw -> <b>Confirm -></b> Take cash -> Finished? -> Take card{' '}
        </div>
        <div>{sessionStorage.getItem('amount')}</div>
        <h1>Please confirm the withdraw of {sessionStorage.getItem('amount')} NOK </h1>
        <CssBaseline /> {/*https://material-ui.com/style/css-baseline */}
        <form onSubmit={this.handleSubmit}>
          <br />
          {/* Bytt ut med CSS block elementer eller noe slikt, bytt name på form fields til å hentes via JS  */}
          <div className="container">
            <Button type="submit" variant="contained" color="primary" className="floatRight">
              Confirm
            </Button>
            <Button type="submit" variant="contained" color="secondary" className="floatLeft">
              Cancel
            </Button>
          </div>
        </form>
      </React.Fragment>
    );
  }
}
export default confirmWithdraw;
Kristian Munter
  • 107
  • 1
  • 1
  • 7
  • 1
    Can you confirm that the component does re-render after you submit? – DSCH Nov 06 '18 at 11:18
  • does backend respond with status 200? – simka Nov 06 '18 at 11:19
  • export the component by connecting it with `withRouter` HOC, `export default withRouter(confirmWithdraw);` Also as a convention your React components name must begin with uppercase characters – Shubham Khatri Nov 06 '18 at 11:27
  • are you sure that `.then(() => this.setState({ redirect: true }));` is actually executed? The answer to this post might solve your problem, but your original approach was ok, there must be something else not working. – c-chavez Nov 06 '18 at 16:27

1 Answers1

10

By assuming you are using react-router v4, you will want to use history object to navigate.

import { withRouter } from 'react-router';
...

handleSubmit = () => {
  ...
  this.props.history.push('/moneyform');
}

render() {
  return (
    <ReactFragment>
      <div>
      ...
    </ReactFragment>
  )
}


export default withRouter(confirmWithdraw);
emil
  • 4,978
  • 3
  • 23
  • 34
  • this is one of the possible solution, but what OP used should also ideally work – Shubham Khatri Nov 06 '18 at 11:26
  • @ShubhamKhatri, still requires withRouter I guess. – emil Nov 06 '18 at 13:57
  • @emil, it doesn't require withRouter if the component you have Redirect in is getting the Router props. https://stackoverflow.com/questions/44009618/uncaught-typeerror-cannot-read-property-push-of-undefined-react-router-dom/44009788#44009788 answer I wrote some time back actually would explain it in more detail – Shubham Khatri Nov 06 '18 at 17:27