Search code examples
elm

Elm Http.post needs to produces Http.Request Int but send needs Http.Request String


I decode response from Http.post request, where return type is Integer:

responseDecoder : Decoder Int
responseDecoder =
   field "data" (field "createDeadline" (field "id" int))

My problem is that I use Http.send which needs String:

createDeadline value =
    Http.send Resolved (Http.post deadlineUrl (encodeBody value |> Http.jsonBody) responseDecoder)

And I dont know how to change the return type. My error message is following:

The 2nd argument to `send` is not what I expect:

113|     Http.send Resolved (Http.post deadlineUrl (encodeBody value |> Http.jsonBody) responseDecoder)
                             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
This `post` call produces:

    Http.Request Int

But `send` needs the 2nd argument to be:

    Http.Request String

Hint: I always figure out the argument types from left to right. If an argument
is acceptable, I assume it is “correct” and move on. So the problem may actually
be in one of the previous arguments!

Hint: Want to convert an Int into a String? Use the String.fromInt function!

Can anyone help with this? I'm just playing around with Elm, but I got stuck here.


Solution

  • My problem is that I use Http.send which needs String

    According to the docs, send function requires the argument to be of type Request a, where a can be any type (Int or String or something else).

    The problem that you have is just what the hint in the compile error says:

    Hint: I always figure out the argument types from left to right. If an argument is acceptable, I assume it is “correct” and move on. So the problem may actually be in one of the previous arguments!

    Thus, it seems that you've already defined somewhere, that you're expecting String and the compiler infered the type to Request String. For example, you might have the Resolved defined something like the following:

    type Msg = Resolved (Result Http.Error String)
    

    And the compiler inferred the polymorphic type of send : (Result Error a -> msg) -> Request a -> Cmd msg to something specific, because it already sees that the first argument is or type (Result Error String -> msg):

    send : (Result Error String -> msg) -> Request String -> Cmd msg
    

    So, in this case the solution is either to change the expecting type:

    type Msg = Resolved (Result Http.Error Int)
    

    Or change the decoder and decode the response to String:

    responseDecoder : Decoder String
    responseDecoder =
       Json.Decode.map String.fromInt (field "data" (field "createDeadline" (field "id" int)))