2

I have a React component with a form that has an action like so:

<center>
    <Form
        action={`/api/sets/`}
        method="post"
        onSubmit={this.onSubmit}>

        <Button color="primary" type="submit">
            Finish
        </Button>
    </Form>
</center >

The onSubmit function looks like this:

onSubmit = (e) => {
    e.preventDefault()
    window.location = "/workout-history";
    e.target.submit()
}

The action to /api/sets/ happens after clicking the button and the onSubmit function does get called but the page isn't redirected. In the post to /api/sets I am returning status 204 so that shouldn't determine where it goes. I am guessing it's possible the function gets called first then the action gets called. Any ideas on how to call the forms action and redirect the page elsewhere?

Slaknation
  • 1,604
  • 2
  • 15
  • 30

2 Answers2

1

You can use import react-router-dom for redirecting.

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


onSubmit = () => {
      return <Redirect to='/target' />
  }

you can view more in : https://medium.com/@anneeb/redirecting-in-react-4de5e517354a

0

The answer you are looking for is probably this.

Prefer using withRouter HOC and call history.push('/new-location') in onSubmit function.

Ganapati V S
  • 1,193
  • 8
  • 20