2017-11-15 10 views
0

セッションを維持するために動作する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はニレに話しているように、しかし、デコーダは失敗しているようです。何か案は?

+1

'localStorage.session'は実際にjavascriptで有効ですか?この[あなたのコードの縮小](https://ellie-app.com/cMg8ZtQqMa1/0)はうまく動作します –

+0

あなたはそれを釘付けにしました。セッションをJSONではなくJSON文字列として保存していました。これは 'app.ports.onSessionChange.send(JSON.parse(localStorage.session));'を使用すると動作します。これを答えると、私は正しいとマークします。 –

答えて

1

コードをminimal working exampleに差し込みましたが、すべて正常です。有効なJSON値であることを確認するために、JavaScriptの部分の中からlocalStorage.sessionの値をログに記録することをお勧めします。

+0

OPのコメントで述べたように、私のJSは実際のJSONではなくJSON文字列を返していました。 –

関連する問題