lue-bird / elm-state-interface / Web.LocalStorage

Saved data for the url origin (protocol, host name, port) across browser sessions.

This data doesn't expire and won't be cleared when the page is closed. The only exception is "incognito mode", where all data is cleared once the last "private" tab is closed.

see mdn on Window.localStorage

request : String -> Web.Interface (Maybe String)

An Interface for reading the value of the entry with the given key. Comes back with Nothing if that key doesn't exist.

import Json.Decode
import Web

projectFromLocalStorageRequest : Web.Interface (Result String Project)
projectFromLocalStorageRequest =
    Web.LocalStorage.request "project"
        |> Web.interfaceFutureMap
            (\savedProject ->
                case savedProject of
                    Nothing ->
                        "nothing had been saved" |> Err

                    Just savedProjectJsonString ->
                        savedProjectJsonString
                            |> Json.Decode.decodeString projectJsonDecoder
                            |> Result.mapError Json.Decode.errorToString
            )

set : String -> String -> Web.Interface future_

An Interface for replacing the value of the entry with the given key or adding key and value as a new entry if the key doesn't exist.

import Json.Decode
import Web

projectSaveToLocalStorage : Project -> Web.Interface future_
projectSaveToLocalStorage =
    \project ->
        Web.LocalStorage.set "project"
            (project |> projectJsonEncode |> Json.Encode.encode 0)

Note: This will trigger an event for all other tabs of the same url origin that can be listened to using setOnADifferentTabListen

remove : String -> Web.Interface future_

An Interface for deleting the entry with the given key if it exists.

Note: This will trigger an event for all other tabs of the same url origin that can be listened to using removeOnADifferentTabListen

setOnADifferentTabListen : String -> Web.Interface { appUrl : AppUrl, oldValue : Maybe String, newValue : String }

An Interface for keeping an eye on when the local storage on a different tab with the same url origin is set.

When the oldValue is Nothing, no entry with that key existed.

removeOnADifferentTabListen : String -> Web.Interface AppUrl

An Interface for keeping an eye on when the local storage on a different tab with the same url origin is removed.