Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

101
Views
How to detect route change via browser back/forward button in MobX Router transition hook?

Imagine we have the following two routes:

viewRoute = {
    name: "View Route",
    pattern: "/route/view"
}

editRoute = {
    name: "Edit Route",
    pattern: "/route/edit",
    beforeExit: (fromState, toState, routerStore) => {
        if (/* route change was triggered by browser button */) {
            if (confirm("Do you want to discard changes?") {
                return toState;
            }
            else {
                return fromState;
            }
        }
    }
}

If the user redirects from "edit" to "view" route by clicking "cancel" or "save" buttons, I don't want to show the discard-confirm dialog. But if they use the browser buttons, I do.

How can I determine within a route transition hook whether that route change was triggered by a browser button? Or alternatively, by a direct call to routerStore.goTo()?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I found a way to identify if a route was changed via button click, by leveraging RouterState.options to pass custom state to the transition hook.

From component:

const Component = () => {
    const cancelEditing = () => {
        routerStore.goTo("Edit Route", {}, {ignoreDiscard: true});
    }

    return <button onClick={cancelEditing}>{"Cancel"}</button>;
}

From Transition Hook:

beforeExit: (fromState, toState) => {
    if (!toState.options.ignoreDiscard) {
        if (confirm("Do you want to discard changes?") {
            return toState;
        }
        else {
            return fromState;
        }
    }
}

This state isn't persisted, so clicking browser back/forward buttons will always result in a dialog popup.

Unfortunately this method can only be achieved by calling RouterStore.goTo() directly as there's no prop on RouterLink called options.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!