|
| 1 | +module Ports.SimpleLogout exposing (..) |
| 2 | + |
| 3 | +{-| ---------------------------------------------------------------------------- |
| 4 | + From the example in Slack |
| 5 | + ============================================================================ |
| 6 | + Here we have everything contained in the one file, unlike our `LocalStorage.elm` |
| 7 | + example. We start with a flag that may be `Nothing` and we've got two functions |
| 8 | + that set login/logout. Unlike `LocalStorage.elm`, our update function is simple |
| 9 | + and doesn't attempt to `Cmd.batch` our commands. It's one `Cmd` to login, and |
| 10 | + one to logout. |
| 11 | +
|
| 12 | + Pushing our changes The JS side would look like: |
| 13 | +
|
| 14 | + ```js |
| 15 | + const localStorageAuthKey = "my-app-auth"; |
| 16 | + const auth = localStorage.getItem(localStorageAuthKey); |
| 17 | + const app = Elm.Main.init(someNode, {auth}); |
| 18 | +
|
| 19 | + app.ports.persistLogin.subscribe((auth) => localStorage.setItem(localStorageAuthKey,auth)); |
| 20 | + app.ports.persistLogout.subscribe(() => localStorage.removeItem(localStorageAuthKey)); |
| 21 | + ``` |
| 22 | +
|
| 23 | + You might also like to check if the function exists as Ryan Haskell suggests. |
| 24 | + If it doesn't exist, you can use a default value or do nothing ... |
| 25 | + @ https://www.youtube.com/watch?v=YfS5BJ4IXcQ |
| 26 | +
|
| 27 | + ```js |
| 28 | + if (app.ports?.persistLogin?.subscribe) { |
| 29 | + app.ports.persistLogin.subscribe((auth) => localStorage.setItem |
| 30 | + } |
| 31 | + ``` |
| 32 | +-} |
| 33 | + |
| 34 | +port persistLogin : String -> Cmd msg |
| 35 | +port persistLogout : () -> Cmd msg |
| 36 | + |
| 37 | +type alias Flags = |
| 38 | + { auth : Maybe String } |
| 39 | + |
| 40 | +type alias Model = |
| 41 | + { auth : Maybe String } |
| 42 | + |
| 43 | +type Msg |
| 44 | + = LogIn String |
| 45 | + | LogOut |
| 46 | + |
| 47 | +init : Flags -> (Model, Cmd Msg) |
| 48 | +init flags = |
| 49 | + ( { auth = flags.auth } |
| 50 | + , Cmd.none |
| 51 | + ) |
| 52 | + |
| 53 | +update msg model = |
| 54 | + case msg of |
| 55 | + LogIn auth -> ({ model | auth = Just auth }, persistLogin auth) |
| 56 | + LogOut -> ({ model | auth = Nothing }, persistLogout ()) |
0 commit comments