Zaid-Ajaj / Feliz.Router

A router component for React and Elmish that is focused, powerful and extremely easy to use.
MIT License
78 stars 16 forks source link

BeforeNavigation with cancellation (or something similar) #51

Closed AkosLukacs closed 1 year ago

AkosLukacs commented 2 years ago

Hi Zaid!

A use case: The user is on a form, with some unsaved data, and clicks on a link that causes navigation (either by accident, or simply haven't thought about saving, because nowadays everything instant-syncs & saves data). If I'm correct, there is no way to catch this "event", and ask the user if they want to save, or just discard the data?

Or can I do this now? Either directly with Feliz.Router, or by subscribing to hashChange or similar event? Or if currently not supported, can I ask for this feature? :)

Thanks!

Zaid-Ajaj commented 1 year ago

if you enable programmatic navigation (even for hyper links on anchor tags) then you can choose when you want to actually navigate away from the page or not:

type Msg =
 | NavigateTo of string

let update msg state =
  match msg with
  | NavigateTo href -> state, Cmd.navigatePath(href)

let goToUrl (dispatch: Msg -> unit) (href: string) (e: MouseEvent) =
    // disable full page refresh
    e.preventDefault()
    // dispatch msg
    dispatch (NavigateTo href)

let render state dispatch =
  let href = Router.format("some-sub-path")
  Html.a [
    prop.text "Click me"
    prop.href href
    prop.onClick (goToUrl dispatch href)
  ]