Local Storage

This is a minimal example of how to use `localStorage` through ports. github

It remembers user data across sessions. This data may be lost if the user clears their cookies, so it is safest to think of this as a cache rather than normal storage.

git clone https://github.com/elm-community/js-integration-examples.git cd js-integration-examples/localStorage elm make src/Main.elm --output=elm.js open index.html

Some terminals may not have an open command, in which case you should open the index.html file in your browser another way.

localStorage

https://wiki.ralfbarkow.ch/assets/localStorage/index.html

index.html

[…] <script type="text/javascript"> // Extract the stored data from previous sessions. var storedData = localStorage.getItem('myapp-model'); var flags = storedData ? JSON.parse(storedData) : null; // Load the Elm app, passing in the stored data. var app = Elm.Main.init({ node: document.getElementById('myapp'), flags: flags }); // Listen for commands from the `setStorage` port. // Turn the data to a string and put it in localStorage. app.ports.setStorage.subscribe(function(state) { localStorage.setItem('myapp-model', JSON.stringify(state)); }); </script> […]

Main.elm

[…] -- Here we use "flags" to load information in from localStorage. The -- data comes in as a JS value, so we define a `decoder` at the bottom -- of this file to turn it into an Elm value. -- -- Check out index.html to see the corresponding code on the JS side. -- init : E.Value -> ( Model, Cmd Msg ) init flags = ( case D.decodeValue decoder flags of Ok model -> model Err _ -> { name = "", email = "" } , Cmd.none ) […] -- JSON ENCODE/DECODE encode : Model -> E.Value encode model = E.object [ ("name", E.string model.name) , ("email", E.string model.email) ] decoder : D.Decoder Model decoder = D.map2 Model (D.field "name" D.string) (D.field "email" D.string)