Custom TypesのデータをJS界に受け渡しする(Elm)
Elmでアプリケーションの状態をlocalStorageに保存しとくようなものを作っていて、カスタムタイプはどうするのか知らなかったのでメモ。
雑にそのままportに渡そうとしたところ、以下のコンパイルエラーが出てきました。
The
setStorage
port is trying to transmit aColorTheme
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しているだけです。