How to go back to the previous url without query params in react router

Viewed 687

I am in a situation where I want to go back to the previous url without query after submitting the form and the form is multiStep so already the url changed many times because of query params.

For example:

I started from https://localhost:3000/admin/users then to create a new user. I visited https://localhost:3000/new-user while completing the form. Queryparameters were added so many times the url became https://localhost:3000/new-user?userType=2&page=1

Now after submitting it I want to go back to url from where i started https://localhost:3000/admin/users but I can't hardcode the path because I'll be using the same form at other place also. How can I do so ?

2 Answers

Edit: Sorry didn't notice you're using reach-router.

So in reach-router it's like this:

const Invoices = ({ navigate }) => (
  <div>
    <NewInvoiceForm
      onSubmit={async event => {
        const newInvoice = await createInvoice(
          event.target
        )
        // we pass -1 to the navigate prop to go to previous route
        navigate(-1)
      }}
    />
  </div>
)
;<Router>
  <Invoices path="invoices" />
  <Invoice path="invoices/:id" />
</Router>

you can store the path before filling out the form,

const { pathname } = useLocation()

after sucessfully submitting the form you can go to the saved path

history = useHistory()
history.push(pathname)
Related