旧gaaamiiのブログ

間違ったことを書いている時があります。コメントやTwitter、ブコメなどでご指摘ください

Custom TypesのデータをJS界に受け渡しする(Elm)

Elmでアプリケーションの状態をlocalStorageに保存しとくようなものを作っていて、カスタムタイプはどうするのか知らなかったのでメモ。

雑にそのままportに渡そうとしたところ、以下のコンパイルエラーが出てきました。

The setStorage port is trying to transmit a ColorTheme value:

259| port setStorage : ModelExposedToStorage -> Cmd msg

I cannot handle that. The types that CAN flow in and out of Elm include:

Ints, Floats, Bools, Strings, Maybes, Lists, Arrays, tuples, records, and JSON values.

Since JSON values can flow through, you can use JSON encoders and decoders to allow other types through as well. More advanced users often just do everything with encoders and decoders for more control and better errors.

上の ColorThemeというのが、localStorageに保存したかったけどできなかったカスタムタイプのデータですね。具体的にはこういうものです。

type ColorTheme = WhiteTheme | DarkTheme

で、エラーに出ている通り、

Since JSON values can flow through, you can use JSON encoders and decoders to allow other types through as well. More advanced users often just do everything with encoders and decoders for more control and better errors.

JSON encodersとdecodersとやらを使えばいいようです。

対応

こんな感じの変更を入れました

どういうこと?

localStorageに保存するときにJSONの形にencodeして、localStorageから取り出してきたときにはElmのデータにdecodeしてます。問題になったColorThemeのところは、こんな感じでcaseで文字列にしたやつをencodeしているだけです。