1

I am having an issue with updating a model from a JSON response through one of my actions. Here is the setup:

I have models that looks like this:

type alias Model =
  { totals: Totals.Total // all values are initialized as 0 or 0.0
  }

-- In other module

type alias Total =
  { days : Int
  , avgPerDay: Float
  , reports : Int
  , people : Int
  , locations : Int
  , totalCoffees : Int
  , coffeesPerDay: Float
  }

A decoder for said model:

decodeTotal : Json.Decoder Total
decodeTotal =
  object7 Total
      ("days" := Json.int)
      ("avgPerDay" := Json.float)
      ("reports" := Json.int)
      ("people" := Json.int)
      ("locations" := Json.int)
      ("totalCoffees" := Json.int)
      ("coffeesPerDay" := Json.float)

To update the model, the following Http request is called:

getTotals : Effects Action
getTotals =
  Http.get Totals.decodeTotal ("/reports/totals")
    |> Task.toMaybe
    |> Task.map TotalsFetched
    |> Effects.task

The response from the server is 200 OK with this body: {"days":347,"reports":1793,"avgPerDay":5.167147,"people":205,"locations":332,"coffees":146,"coffeesPerDay":0.42074928}

However, in the TotalsFetched Action:

update : Action -> Model -> (Model, Effects Action)
update action model =
  case action of
    TotalsFetched totals ->
      log (toString totals)  -- logs Nothing
      ( { model | totals = Maybe.withDefault model.totals totals }
      , Effects.none
      )

I am assuming that since totals is Nothing my model just stays as is described in the Maybe.withDefault

I don't understand why totals is Nothing instead of the Decoded response from the server. This is my first elm project, so I wouldn't be surprised if I am missing something really obvious to the trained eye.

sambev
  • 131
  • 7

1 Answers1

1

Your json is returning a field called coffees while your decoder is looking for totalCoffees.

You may want to consider using Task.toResult instead of Task.toMaybe because that way you'll get an error message returned when something goes wrong.

Chad Gilbert
  • 36,115
  • 4
  • 89
  • 97
  • That was it. Thanks for noticing the tiny error and the suggestion to use `Task.toResult`. The silent failure made this hard to reason about. – sambev Jan 03 '16 at 21:49