rgrempel / elm-route-url

Router for single-page-apps in Elm
http://package.elm-lang.org/packages/rgrempel/elm-route-url/latest
MIT License
196 stars 16 forks source link

How to do a "redirect" #12

Closed LeonLiuY closed 8 years ago

LeonLiuY commented 8 years ago

When I open the root page /#!/, I want to redirect to the Home page /#!/home, and change the hash.

I could render the home page correctly by adding this in location2action

calse list of
  [ "home" ] ->
    [ ShowPage Home ]

  [ "" ] ->
    [ ShowPage Home ]

But it won't change the URL.

Then how to make a "redirect"?

rgrempel commented 8 years ago

I suppose you could fall back on the History module and use History.setPath, History.replacePath or possibly History.setHash (in the latest version), depending on whether you want to generate a history entry or not.

That is, the location2action for "" would not show the page directly ... instead, it would return a different action that would use one of the History methods (as an effect) to set the URL you want. That, in turn, would trigger a second round of location2action, which would now be for "home", which you'd handle normally.

At least, I think that sort of thing ought to work -- I haven't tried it lately.

The other possible approach would be to do something with deltaToUpdate that returns a HashUpdate to the desired URL. However, I have a feeling that might not work, because I think I disabled deltaToUpdate while processing the actions returned by location2action ... I was getting some infinite loops otherwise.

LeonLiuY commented 8 years ago

Thanks @rgrempel !

I have succeeded:

type Action 
  = ...
  | Redirect String
  | NoOp

location2action list = 
  case list of
    [ "" ] ->
      [ Redirect "home"]

update action model =
  case action of

    Redirect url ->
      ( model, History.replacePath (prefix ++ url) |> Task.map (\()-> NoOp) |> Effects.task)