1

I am exploring ELM and trying to access web api. I followed the this link.

I am able to hit my service and getting the response (Showing in browser network tab), but failure code portion is executing from elm update.

Implementation

---Model 
type alias Model =
    { 
      message : String,
    }

model:Model
model = {
    message = "Hello"
    }


--update


postRequest : Http.Request
postRequest =
    { verb = "POST"
    , headers =
        [("Content-Type", "application/json")
        ]
    , url = "http://xyz/events/list"
    , body = Http.string """{ "domainId": 1 }"""
    }

getEventList: Cmd Msg
getEventList = 
      Task.perform Messages.FetchFail Messages.FetchSucceed (Http.fromJson decodeString (Http.send Http.defaultSettings postRequest))



update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
    case msg of
        Messages.NoOp ->
            ( model, Cmd.none )
        Messages.FetchSucceed xy->
            ({model| message = "success"},Cmd.none)
        Messages.FetchFail _->
            ({model |message = "fail"} ,Cmd.none)

API response :

{   "message": "",   "data": [
    {
      "eventId": 104,
      "title": "private Events",
      "description": "abc",
      "businessId": 51,
      "businessTitle": "VampireDA_Adda",
      "startDate": "2016-07-08" 
    },
    {
      "eventId": 107,
      "title": "Event weekly Midnight",
      "description": "xyz",
      "businessId": 44,
      "businessTitle": "Spanish Scotch",
      "startDate": "2016-07-08"          

    }] }

Please help me, if i have implement any thing wrong.

and also how i can decode json to model (fill model with response json)?

Simon H
  • 20,332
  • 14
  • 71
  • 128
Manu Chawla
  • 327
  • 1
  • 12

1 Answers1

3

you are probably getting the error because the decoding is not working out. But first try to get used to piping

Http.send Http.defaultSettings postRequest
|> Http.fromJson decodeString
|> Task.perform Messages.FetchFail Messages.FetchSucceed

To decode you need an Elm record

type alias DataItem = 
    { eventId: Int
    , title: String
    , description : String
    , businessId : Int
    , businessTitle : String
    , startDate: String
    }

The decoder will then look something like

dataDecoder = 
    object6 DataItem
    ("eventId" := int)
    ("title" := string)
    ("description" := string)
    ("businessId" := int)
    ("businessTitle" := string)
    ("startDate" := string)

decoder = at ["data"] (list dataDecoder)

Decoders take a bit of getting used to, so I created a site to help you practise: http://simonh1000.github.io/decoder/

Simon H
  • 20,332
  • 14
  • 71
  • 128