How to send a parametrized message to update function?

Hi! I’m not capable of understanding how to send a parametrized message to the update function when I receive a service response.

I mean, having the next types and functions:

type Message = 
    ApiCall (Result Error ApiCallResult) 

type ApiCallResult = 
    GetSections (List Section)

api : (Result Error ApiCallResult) -> Model -> (Model, Cmd Message)
api result model = case result of
    Ok call -> case call of
       GetSections _ -> (model, Cmd.none)
    Err _ -> (model, Cmd.none)

update msg model = case msg of
    ApiCall result -> api result model

I resolve the service calling like this:

sectionDecoder : D.Decoder Section

getSections : Cmd Message
getSections = 
    Http.get {
        url = "http://127.0.0.1:8000/api/sections/",
        expect = H.expectJson (ApiCall GetSections) (Decoder.list sectionDecoder)
        }

However, it’s clear that the expect parameter for the Http.get is wrong. The compiler gives the next error.

The 1st argument to `expectJson` is not what I expect:

45|         expect = Http.expectJson (ApiCall GetSections) (Decoder.list sectionDecoder)
                                   ^^^^^^^^^^^^^^^^^^^^^^^
This `ApiCall` call produces:

    T.Message

But `expectJson` needs the 1st argument to be:

    Result H.Error a -> msg

-- TYPE MISMATCH --------------------------------------------------- src/Api.elm

The 1st argument to `ApiCall` is not what I expect:

45|         expect = Http.expectJson (ApiCall GetSections) (Decoder.list sectionDecoder)
                                             ^^^^^^^^^^^^^
This `GetSections` value is a:

    List Section -> ApiCallResult

But `ApiCall` needs the 1st argument to be:

    Result Error ApiCallResult

Detected problems in 1 module.

Could you make me understand how to do it? Thanks!

It looks like you’re trying to construct a ApiCall with GetSections. Pretend for a minute those are just regular functions. You couldn’t call ApiCall with GetSections because ApiCall expects a result, and GetSections is a function that takes List Section and returns an ApiCallResult. In other words, they don’t compose the way you want here.

So there are two problems here:

  1. expectJson expects you to handle the error. Looks like you’ve already got a type that accepts a Result: ApiCall. We can just use that directly.
  2. the success value in the Result should be an ApiCallResult but currently it’s a List Section. Looks like you’re trying to wrap that in the first argument, but it needs to happen in the decoder instead.

So this code might set you straight:

expectJson ApiCall (Decode.map GetSections (Decode.list sectionDecoder))

Thanks! I’ll give some thoughts to it to fully understand!

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.