Reputation: 18132
I have a static page with two components.
Is there a way to share a state (let say the access_token to the API for instance) between those two components?
I could add ports to each components that would update a localStorage key and send the store to each other components.
But is there a better way for this?
Upvotes: 0
Views: 318
Reputation: 18132
The solution I ended-up with was to use two ports:
port saveStore : String -> Cmd msg
port storeChanged : (String -> msg) -> Sub msg
With decoders and encoders:
serializeStore : AccessToken -> Profile -> Cmd Msg
serializeStore access_token profile =
encodeStore access_token profile
|> saveStore
encodeStore : AccessToken -> Profile -> String
encodeStore access_token profile =
let
encoded =
Encode.object
[ ( "access_token", tokenToString access_token |> Encode.string )
, ( "profile", encodeUserProfile profile )
]
in
Encode.encode 0 encoded
deserializeStore : String -> Maybe Store
deserializeStore =
Decode.decodeString decodeStore >> Result.toMaybe
decodeStore : Decoder Store
decodeStore =
Decode.map2 Store
decodeToken
(Decode.field "profile" decodeProfile)
decodeToken : Decoder AccessToken
decodeToken =
Decode.field "access_token" Decode.string
|> Decode.andThen
(\token ->
stringToToken token
|> Decode.succeed
)
And then I use them to sync my component store and keep a copy on the localStorage:
<script src="app.js"></script>
<script>
// The localStorage key to use to store serialized session data
const storeKey = "store";
const headerElement = document.getElementById("header-app");
const headerApp = Elm.Header.init({
node: element,
flags: {
rawStore: localStorage[storeKey] || ""
}
});
const contentElement = document.getElementById("content-app");
const contentApp = Elm.Content.init({
node: element,
flags: {
rawStore: localStorage[storeKey] || ""
}
});
headerApp.ports.saveStore.subscribe((rawStore) => {
localStorage[storeKey] = rawStore;
contentApp.ports.storeChanged.send(rawStore);
});
contentApp.ports.saveStore.subscribe((rawStore) => {
localStorage[storeKey] = rawStore;
headerApp.ports.storeChanged.send(rawStore);
});
// Ensure session is refreshed when it changes in another tab/window
window.addEventListener("storage", (event) => {
if (event.storageArea === localStorage && event.key === storeKey) {
headerApp.ports.storeChanged.send(event.newValue);
contentApp.ports.storeChanged.send(event.newValue);
}
}, false);
</script>
Upvotes: 2