セッションを維持するために動作するelmポートを取得しようとしています。elmポートからセッションをデコードできません。
window.addEventListener("load", function(event) {
app.ports.onSessionChange.send(localStorage.session);
}, false);
localStorage.session
はこのようになります(と私がログアウトするまで、それはそこにとどまる):
{"email":"[email protected]","token":"eyJhbG...","user_id":1,"handle":"me"}
定義で
のindex.htmlでは、スクリプトは次のリスナーが含まPorts.elm
は次のとおりです。
port onSessionChange : (Value -> msg) -> Sub msg
このポートは、ここでMain.elm
に接続されている(私は下記の定義の一部含めることを忘れてしまった場合は私に知らせて):コンソールで
subscriptions : Model -> Sub Msg
subscriptions model =
Ports.onSessionChange sessionChange
sessionChange : Json.Decode.Value -> Msg
sessionChange value =
let
result =
Json.Decode.decodeValue sessionDecoder value
in
case result of
Ok sess ->
SetSession (Just sess)
Err err ->
SetSession Nothing
...
type alias Session =
{ email : String
, token : String
, user_id : Int
, handle : String
}
...
import Json.Decode as Decode exposing (..)
import Json.Decode.Pipeline as Pipeline exposing (decode, required)
sessionDecoder : Decode.Decoder Session
sessionDecoder =
Pipeline.decode Session
|> Pipeline.required "email" Decode.string
|> Pipeline.required "token" Decode.string
|> Pipeline.required "user_id" Decode.int
|> Pipeline.required "handle" Decode.string
...
type Msg
= NoOp
| SetSession (Maybe Session)
...
update msg model =
case msg of
SetSession session ->
case Debug.log "session = " session of
Just sess ->
({ model | session = sess } , Cmd.none)
Nothing ->
(model, Cmd.none)
Debug.log "session"
ディスプレイNothing
をページのロード時、JSはニレに話しているように、しかし、デコーダは失敗しているようです。何か案は?
'localStorage.session'は実際にjavascriptで有効ですか?この[あなたのコードの縮小](https://ellie-app.com/cMg8ZtQqMa1/0)はうまく動作します –
あなたはそれを釘付けにしました。セッションをJSONではなくJSON文字列として保存していました。これは 'app.ports.onSessionChange.send(JSON.parse(localStorage.session));'を使用すると動作します。これを答えると、私は正しいとマークします。 –