榆树0.17:Task.perform和Maybe

时间:2016-06-16 00:10:37

标签: elm

我希望有人可以帮助我使用Task.perform,因为我并不真正理解如何处理一个可能的回复 - 并且文档并没有让我更清楚。

在我的modelresults Maybe项目列表或Nothing

-- model

type alias Item =
  { name : String}

type alias Model =
  { results : Maybe (List Item) }

model = {
  results = Nothing
}

我执行任务并对其进行解码:

-- Task

fetch : String -> Cmd Msg
fetch query =
  let url =
    "https://some_url" ++ query
  in
    Task.perform FetchFail FetchSuccess (Http.get decode url)


-- decoder

decoder: Json.Decoder (List Item)
decoder =
  Json.at ["data"] (Json.list nestedListDecoder)


-- nestedListDecoder

nestedListDecoder : Json.Decoder Item
nestedListDecoder =
  Json.object1 Item
    ("name" := Json.string)

然后我在更新中处理响应:

-- update

type Msg
  = FetchSuccess (Maybe (List Item))
  | FetchFail Http.Error


update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
  case msg of
    FetchSuccess results ->
      case results of
        Nothing ->
          ( { model | results = Nothing}, Cmd.none)
        Just res ->
          ( { model | results = res }, Cmd.none)

    FetchFail err ->
      -- ... handle error

并且在视图中迎合了Maybe:

-- view

result : Item -> Html Msg
result item =
  li [] [ text item.name ]


view : Model -> Html Msg
view model =
  ul [ ] (List.map result (Maybe.withDefault [] model.results))

我在处理Maybe结果时收到此错误。

198|     Task.perform FetchFail FetchSuccess (Http.get repos url)
                                              ^^^^^^^^^^^^^^^^^^
Function `perform` is expecting the 3rd argument to be:

    Task Http.Error (Maybe (List Repo))

But it is:

    Task Http.Error (List Repo)

任何人都可以建议我需要哪个地方来迎合Maybe

1 个答案:

答案 0 :(得分:1)

decoder进行简单的调整就可以解决问题。解码器只需使用Json.Decode.maybe

decoder: Json.Decoder (Maybe (List Item))
decoder =
  Json.maybe <| Json.at ["data"] (Json.list nestedListDecoder)
相关问题