I am trying to load a json from localstorage with this code:
let
val = Storage.getItem "exercises" decodeExerciseList
in
({ model | exercises = val }, Cmd.none)
but I am getting this error:
The 5th and 6th branches of this case
produce different types of values. - The 5th branch has this type:
( Model, Cmd Msg )
But the 6th is:
( { exercise : Maybe Model.Exercise
, exercises : Task String (List Model.Exercise)
}
, Cmd msg
)
I thought maybe this could help:
case val of
succeed -> ({ model | exercises = val }, Cmd.none)
fail -> ({model | exercises = []}, Cmd.none)
but no luck. in this case I got this other error:
The 1st and 2nd branches of this case
produce different types of values. - The 1st branch has this type:
( { ..., exercises : Task String (List Model.Exercise) }, Cmd msg )
But the 2nd is:
( { ..., exercises : List a }, Cmd msg )
so basically I am still having the issue with the Task String X instead of just X.
any idea of what to do here?
Although localstorage is access synchronously in javascript, such access is still impure and is thus handled in Elm using tasks as you have seen.
So you code needs to work in 2 stages - initiating the Task - using the returned result
Something like the following
type Msg
= LoadFromStorage
| OnLocalStorage (Result String (List Model.Exercise))
update message model =
case message of
LoadLocalStorage ->
( model
, Storage.getItem "exercises" decodeExerciseList
|> Task.attempt OnLocalStorage
)
OnLocalStorage res ->
case res of
Ok val ->
({ model | exercises = val }, Cmd.none)
Err err ->
handle error
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With